HandsOn Assigning Values to Variables

1. If the Visual Basic window is not open, press Alt+F11 to open it. Next, choose Insert | Module to add a new module.

2. Enter the code of the CalcCost procedure in the new module's Code window.

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

Sub CalcCost() slsPrice = 35 slsTax = 0.085

cost = slsPrice + (slsPrice * slsTax)

strMsg = "The calculator total is " & "$" & cost & "." MsgBox strMsg End Sub

The CalcCost procedure uses four variables: slsPrice, slsTax, cost, and strMsg. Because none of these variables have been explicitly declared, they all have the same data type — Variant. The variables slsPrice and slsTax were created by assigning some values to variable names at the beginning of the procedure. The cost variable was assigned a value that is the result of the calculation slsPrice + (slsPrice * slsTax). The cost calculation uses the values supplied by the slsPrice and slsTax variables. The strMsg variable puts together a text message to the user. This message is then displayed with the MsgBox function.

When you assign values to variables, you follow the name of the variable with an equals sign. After the equals sign you enter the value of the variable. This can be a number, expression, or text surrounded by quotation marks. While the values assigned to the variables slsPrice, slsTax, and cost are easily understood, the value stored in the strMsg variable is a little more involved. Let's examine the content of the strMsg variable:

strMsg = "The calculator total is " & "$" & cost & "."

The string "The calculator total is " begins and ends with quotation marks. Notice that there is an extra space before the ending quotation mark.

Introduction to Access 2003 VBA Programming

The & character allows one string to be appended to another string or to the contents of a variable.

The $ is used to denote the currency type. Because the dollar symbol is a character, it is surrounded by quotation marks. The & character must be used every time you want to append a new piece of information to the previous string.

The cost variable is a placeholder. The actual cost of the calculator will be displayed here when the procedure runs. ■ The & character attaches yet another string.

The period is surrounded by quotation marks. When you require a period at the end of the sentence, you must attach it separately when it follows the name of a variable.

0 0

Post a comment