ByRef

This is the default method for passing variables between procedures in Visual Basic; that is, if you specify neither ByVal nor ByRef, VB treats the variable as though it had been specified as ByRef.

ByRef means that the variable is passed by reference. In other words, only a reference to the original variable is passed to the called procedure. The called procedure doesn't get its own copy of the variable; it simply references the original variable. This is very similar in concept to the pointers you find in C and C++. The result is that if you make a change to the variable in the called procedure, that change is reflected in the variable in the calling procedure, because they are actually the same variable.

The code fragment below demonstrates passing a variable by reference. It also demonstrates how to circumvent the problem that a function can only return one value. For example, if the GetValue function you are calling returns an input from the user, how do you determine if the user wants to cancel the input altogether? You can't necessarily do this by using the return value of the function, since it may be a valid input from the user. You therefore pass a Boolean variable by reference and test its value on return from the function:

Private Sub Command1_Click()

Dim blnCancel As Boolean Dim lReturn As Long lReturn = GetValue(blnCancel) If blnCancel Then Exit Sub

50 Chapter 3 - VBA Variables and Data Types

Else

MsgBox lReturn End If

End Sub

Private Function GetValue(ByRef Cancel As Boolean) As Long

Dim sResponse As String Dim iResponse As Integer

Cancel = False sResponse = InputBox(Prompt:="Enter a value", Title:="Input Required", Default:=0)

'an inputbox returns a zero length string if the Cancel button was clicked If sResponse = "" Then Cancel = True

Else

If IsNumeric(sResponse) Then

GetValue = CLng(sResponse) End If End If

End Function

As you can see, ByRef arguments can be extremely useful. For example, you can use a ByRef argument to "return" a value from a subroutine that normally can't return a value. This can be used to great effect to obtain return values from an event handler. And as demonstrated above, you can also use ByRef arguments to return more than the one return value from a function.

Was this article helpful?

0 0

Post a comment