HandsOn Passing Arguments to Subroutines and Functions

1. In the Visual Basic Editor window, choose Insert | Module to add a new module.

2. In the Code window, type the subroutine and function procedure as shown below.

Sub ThreeNumbers()

Dim numl As Integer, num2 As Integer, num3 As Integer numl = 10 num2 = 20 num3 = 30

MsgBox MyAverage(numl, num2, num3) MsgBox numl MsgBox num2 MsgBox num3 End Sub

Function MyAverage(ByVal numl, ByVal num2, ByVal num3) numl = numl + 1

The ThreeNumbers subroutine assigns values to three variables, and then calls the MyAverage function to perform and return the average of the numbers stored in these variables. The function's arguments are the names of the variables: num1, num2, and num3. Notice that all variable names are preceded with the ByVal keyword. Also, notice that prior to the calculation of the average, the MyAverage function changes the value of the num1 variable. Inside the function procedure, the num1 variable equals 11 (10 + 1). Therefore, when the function passes the calculated average to the ThreeNumbers procedure, the MsgBox function displays the result as 20.3333333333333 and not 20, as expected. The next three functions show the contents of each of the variables. The values stored in these variables are the same as the original values assigned to them: 10, 20, and 30.

What will happen if you omit the ByVal keyword in front of the num1 argument in the MyAverage function's declaration line? The function's result will still be the same, but the content of the num1 variable displayed by the MsgBox num1 is now 11. The MyAverage function has not only returned the unexpected result (20.3333333333333 instead of 20), but also has modified the

Introduction to Access 2003 VBA Programming original data stored in the num1 variable. To prevent Visual Basic from permanently changing the values supplied to the function, use the ByVal keyword.

0 0

Post a comment