HandsOn Understanding Module Level Variables

This hands-on requires the prior completion of Hands-On 3-4 and 3-5.

1. In the Code window, in the same module where you entered the CalcCost procedure, cut the declaration line Dim slsTax As Single and paste it at the top of the module sheet, below the Option Explicit statement.

2. Enter the code of the ExpenseRep procedure shown below in the same module where the CalcCost procedure is located.

3. Click anywhere inside the CalcCost procedure and press F5 to run it.

4. As soon as the CalcCost procedure finishes executing, run the ExpenseRep procedure.

Part I

Sub ExpenseRep()

Dim slsPrice As Currency Dim cost As Currency slsPrice = 55.99

cost = slsPrice + (slsPrice * slsTax)

MsgBox slsTax MsgBox cost

End Sub

The ExpenseRep procedure declares two Currency type variables: slsPrice and cost. The slsPrice variable is then assigned a value of 55.99. The slsPrice variable is independent of the slsPrice variable declared within the CalcCost procedure.

The ExpenseRep procedure calculates the cost of a purchase. The cost includes the sales tax. Because the sales tax is the same as the one used in the CalcCost procedure, the slsTax variable has been declared at the module level. After Visual Basic executes the CalcCost procedure, the contents of the slsTax variable equals 0.085. If slsTax were a local variable, upon the termination of the CalcCost procedure, the contents of this variable would be empty. The ExpenseRep procedure ends by displaying the value of the slsTax and cost variables in two separate message boxes.

After running the CalcCost procedure, Visual Basic erases the contents of all the variables except for the slsTax variable, which was declared at a module level. As soon as you attempt to calculate the cost by running the ExpenseRep procedure, Visual Basic retrieves the value of the slsTax variable and uses it in the calculation.

0 0

Post a comment