HandsOn Using Static Variables

1. If the Visual Basic window is not open, press Alt+F11 to open it.

2. Choose Insert | Module to add a new module.

3. Enter the code of the CostOfPurchase procedure shown below in the new module's Code window.

4. To run the procedure, click any line between the Sub and End Sub keywords and press F5 or choose Run | Run Sub/UserForm.

Sub CostOfPurchase() ' declare variables Static allPurchase Dim newPurchase As String Dim purchCost As Single newPurchase = InputBox("Enter the cost of a purchase:") purchCost = CSng(newPurchase) allPurchase = allPurchase + purchCost

' display results

MsgBox "The cost of a new purchase is: " & newPurchase MsgBox "The running cost is: " & allPurchase End Sub

The above procedure begins with declaring a Static variable named allPurchase and two local variables: newPurchase and purchCost. The InputBox function used in this procedure displays a dialog box and waits for the user to enter the value. As soon as the user inputs the value and clicks OK, Visual Basic assigns this value to the newPurchase variable. The InputBox function allows you to get a user's input while the procedure is running. Because the result of the InputBox function is always a string, the newPurchase variable was declared as the String data type. You can't, however, use strings in mathematical

Part I

calculations. That's why the next instruction uses a type conversion function (CSng) to translate the text value into a numeric variable of the Single data type. The CSng function requires one argument: the value you want to translate. The number obtained as the result of the CSng function is then stored in the purchCost variable.

0 0

Post a comment