3.3 ByVal and ByRef

There are two types of parameters, one is “ByVal”, while the other one is “ByRef”.

The example in section 3 illustrates “ByRef”. By default (in Visual Basic 6 and earlier), parameter is passed by reference instead of passed by value. This means that anything that happens to the parameter happens to whatever was used to specify the parameter.

On the other hand, any changes to a ByVal (passed by value) parameter only stays with the parameter.

An example can illustrate this.

Let us example a subroutine as follows:

1Sub Increment(ByVal x As Integer
2  x = x + 1 
3End Sub

Now, consider the following code to use it:

Increment(counter)  
    

This invocation will be useless. This is because a ByVal parameter is merely a copy of whatever is used to specify it. As a result, the actual increment operation only occurs to the copy, not affecting the original.

This problem can be fixed by changing the parameter to a ByRef type as follows:

1Sub Increment(ByRef x As Integer
2  x = x + 1 
3End Sub

Note that while the word ByRef is optional, it is best to use it. This is because VisualBasic.NET changes the default to ByVal (instead of ByRef). An explicit specification makes a subroutine more portable from VB6 (which is the basis of VBA) to VB.net.

In this revise version, the parameter x is an alias of the original item. In the invocation of Increment, counter is used to specify parameter x. As a result, x becomes an alias of counter. Whatever happens to x happens to counter. In this specific case, incrementing by one.