View contents of this chapter

Arguments

When two procedures need to share data, the calling procedure can send its local variables to any called procedure. Both functions and subroutines can take arguments. You already know how to pass arguments to procedures, for example, when you used the InputBox() and the MsgBox() functions.

ByVal and ByRef

When you pass parameters to a subroutine or function, you can do it in two ways: either by value (ByVal) or by reference (ByRef). By reference means that the calling procedure can change the arguments in the called procedure. To the contrary, by value means that the called procedure cannot change the arguments in the calling procedure.

Play Sound By default, all the arguments are passed by reference.

The following example will make the concept clear.

Private Sub Form_Load()
  Dim intCounter as Integer
  intCounter = 1
  Call Increment(intCounter)
  Debug.Print "Value after function is: " & intCounter
End Sub

Private Sub Increment(ByVal intNumber As Integer)
  intNumber = intNumber + 1
  Debug.Print "New value: " & intCounter
End Sub

The program outputs

New Value: 2
Value after function is: 1

intCounter in the Form_Load is unaffected by the addition in Increment(). This is because only the value of intCounter has been passed to intNumber. intNumber is a completely new variable. Now try this example again, but change ByVal in Increment to ByRef as follows:

Private Sub Increment(ByRef intNumber As Integer)
or you can also omit ByRef
Private Sub Increment(intNumber As Integer)

This time the output is

New Value: 2
Value after function is: 2

 



© Universal Teacher Publications        INDEX Previous Screen Next Screen