Passing parameters via ByRef or ByVal

<< Click to Display Table of Contents >>

Passing parameters via ByRef or ByVal

Parameters can be passed to procedures either by reference (ByRef) or by value (ByVal):

ByRef

The ByRef ("by reference") keyword indicates that a parameter is passed in such a way that the invoked procedure can change the value of the underlying variable.
ByRef is the default method for passing parameters and therefore does not have to be explicitly specified. Sub Test(j As Integer) is therefore synonymous with Sub Test(ByRef j As Integer).

ByVal

With ByVal ("by value"), the procedure merely receives a copy of the variable, so that changes to the parameter’s value inside the procedure do not affect the specified variable.
To pass a parameter by value, place the keyword ByVal in front of the parameter: Sub Joe(ByVal j As Integer).
Alternatively, you can achieve this by passing the parameter in parentheses. Here, for example, the parameter Var3 is passed by value:
SubOne Var1, Var2, (Var3)