Passing Arguments by Value

If you pass an argument by value when calling a procedure, the called procedure only receives a copy of the variable passed from the calling procedure. If the called procedure changes the value, the change affects only the copy and not the variable in the calling procedure. Passing by value therefore protects data from being accidentally changed by the called procedure. Use the ByVal keyword to indicate that a variable is passed by value. For example, the following AddThree procedure accepts arguments passed by value. Because the AddThree procedure can only work with a copy of the varToPass variable and cannot access the actual value stored in the varToPass variable, the MsgBox function in TestPassingArgs will display the value 7.


Sub TestPassingArgs()
    varToPass = 7
    AddThree varToPass
    MsgBox varToPass        ' displays 7
End Sub


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

Note that if you specify a data type for an argument passed by value, you don't need to pass a value of that type for the argument. In the preceding example, the varToPass variable is a Variant variable (because it hasn't been assigned any other data type), but Visual Basic passes a copy of it to the AddThree procedure as an integer. For more information about declaring data types, see Chapter 2, "Variables, Constants, and Data Types."

Note that your code cannot pass an argument with a user-defined type by value.