Sometimes to avoid class level or global variables when using a user-defined procedure you will want to pass arguments to the procedure.
To pass arguments to a procedure in Visual Basic you place them after the procedure name in the calling statement. The argument must be enclosed in parenthesis.
:
TotalSales (sngSaleAmount) ‘will pass sngSalesAmount to TotalSales
You may pass more than one arguments at a time.
TotalSales (sngSaleAmount, dblTotalSales)
When we pass something to a procedure we must provide an argument when the procedure is called and also provide a memory location (parameters) in the called procedure to store the argument being passed.
Calling statement
CalculateFICA (decGrossPay)
Called procedure
Private Sub CalculateFICA (ByVal
decPay As Decimal)
:
:
End Sub
The data type must be the same in the calling statement as in the called procedure but the name does not have to be the same. If more than one argument is passed they must be listed in the called procedure in the same order as they were passed. Note: Overloading and optional parameters, which are beyond the scope of this discussion, allow for differences.
Calling statement
TotalSales (intSaleAmount, decTotalSales)
Called procedure
Private Sub TotalSales (ByVal intSaleAmount As Integer, ByVal decTotalSales As Decimal)
:
End Sub
When declaring parameters for a called procedure you must indicate whether the argument will be passed by ByVal (by value) or ByRef (by reference). To indicate which way to pass a value you include the keyword ByVal or ByRef before the parameter. If you leave off the modifier ByVal is supplied by default.
Private Sub CalculateFICA (ByVal decPay As Decimal)
Dim decFICA As Decimal
decFICA =
decPay * .06875D
:
:
End Sub
When passing ByVal the value of the original argument is passed to the called procedure and placed in a new memory location (the parameter variable). There will be two separate copies of the passed value in memory. The original value is Local to the calling procedure, the passed value is Local to the called procedure.
When passed ByVal the value stored in the memory location of the original argument (because it is a different memory location) can NOT be permanently changed by the called procedure.
When passed ByRef the address of the original argument is passed to the called procedure. The parameter (variable) declared in the called procedure contains a reference to (the memory address of) the argument in the calling procedure. If the value of the passed variable is changed in the called procedure the memory location pointed to by that parameter is changed.
When an argument is passed ByRef the value stored in the memory location of the original argument CAN be permanently changed by the called procedure.
If you need to use a variable that is modified by a called procedure you can either
Declare the variable at Class level (discouraged)
OR
pass the variable ByRef.