Passing Arguments by Reference

If you pass an argument by reference when calling a procedure, the procedure has access to the actual variable in memory. As a result, the variable's value can be changed by the procedure. Passing by reference is the default in Visual Basic, so if you don't explicitly specify to pass an argument by value, Visual Basic will pass it by reference. Each of the following lines indicates that an argument is passed by reference.


Sub AddThree(ByRef passedVar As Integer)
Sub AddThree(passedVar As Integer)        'ByRef is the default

The AddThree procedure accepts arguments passed by reference. Because the AddThree procedure changes the value stored in the varToPass variable that's passed to the procedure, the MsgBox function in TestPassingArgs will display the value 10.


Sub TestPassingArgs()
    Dim varToPass As Integer
    varToPass = 7
    AddThree varToPass
    MsgBox varToPass        ' displays 10
End Sub


Sub AddThree(ByRef passedVar As Integer)
    passedVar = passedVar + 3
End Sub

Note that if you specify a data type for an argument passed by reference, you must pass a value of that type for the argument. Failure to do this will result in a type mismatch error. For more information about declaring data types, see Chapter 2, "Variables, Constants, and Data Types."

Passing a variable by reference requires less memory and time than passing by value but increases accessibility to the value stored in the variable and therefore increases the chance that the value will be accidentally changed.