HandsOn Calling a Function From a Procedure

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

2. Enter the following HowMuch subroutine in the Code window:

Sub HowMuch()

Dim num1 As Single Dim num2 As Single Dim result As Single num1 = 45.33 num2 = 19.24

Introduction to Access 2003 VBA Programming result = MultiplyIt(num1, num2)

MsgBox result End Sub

3. Enter the following MultiplyIt function procedure in the Code window below the HowMuch subroutine:

Function MultiplyIt(num1, num2) As Integer

MultiplyIt = num1 * num2 End Function

4. Click anywhere within the HowMuch procedure and press F5 to run it. Because the values stored in the variables num1 and num2 are not whole numbers, to ensure that the result of multiplication is a whole number, you may want to assign the Integer type to the result of the function. If you don't assign the data type to the MultiplyIt function's result, the HowMuch procedure will display the result in the data type specified in the declaration line of the result variable. Instead of 872, the result of the multiplication will be 872.1492.

5. To make the MultiplyIt function more useful, instead of hard coding the values to be used in the multiplication, you can pass different values each time you run the procedure by using the InputBox function. Take a few minutes to modify the HowMuch procedure on your own, following the example of the EnterText subroutine that was created in the preceding hands-on. To pass a specific value from a function to a subroutine, assign the value to the function name. For example, the NumOfDays function shown below passes the value of 7 to the subroutine DaysInAWeek.

Function NumOfDays()

NumOfDays = 7 End Function

Sub DaysInAWeek()

MsgBox "There are " & NumOfDays & " days in a week." End Sub

0 0

Post a comment