Chapter 10 Creating Modules and Procedures 269
procedure are passed back to the calling routine. Passing by reference can have significant
advantages, so long as you’re careful not to change a variable unintentionally in a procedure.
For example, consider the following Sub procedure declaration and call:
Sub CostPlusInterest(ByRef Cost As Single, ByRef Total As Single)
Cost = Cost * 1.05 'add 5% to cost...
Total = Int(Cost) 'then make integer and return
End Sub
.
.
.
Dim Price, TotalPrice As Single
Price = 100
TotalPrice = 0
CostPlusInterest(Price, TotalPrice)
MsgBox(Price & " at 5% interest is " & TotalPrice)
In this example, the programmer passes two single-precision variables by reference to the
CostPlusInterest procedure: Price and TotalPrice. The programmer plans to use the updated
TotalPrice variable in the subsequent MsgBox call but has unfortunately forgotten that the
Price variable was also updated in an intermediate step in the CostPlusInterest procedure.
(Because Price was passed by reference, changes to Cost automatically result in the same
changes to Price .) This produces the following erroneous result when the program is run:
However, the programmer probably wanted to show the following message:
So how should the CostPlusInterest procedure be fixed to produce the desired result? The
easiest way is to declare the Cost argument by using the ByVal keyword, as shown in the
following program statement:
Sub CostPlusInterest(ByVal Cost As Single, ByRef Total As Single)