HandsOn Forcing Declaration of Variables

1. Return to the Code window where you entered the CalcCost procedure (see Hands-On 3-4).

2. At the top of the module window (in the first line), enter Option Explicit and press Enter. Visual Basic will display the statement in blue.

3. Position the insertion point anywhere within the CalcCost procedure and press F5 to run it. Visual Basic displays the error message: "Compile error: Variable not defined."

4. Click OK to exit the message box. Visual Basic selects the name of the variable, slsPrice, and highlights in yellow the name of the procedure, Sub CalcCost(). The title bar displays "Microsoft Visual Basic — Acc2003_Chap03 [break] — [Module4 (Code)]." The Visual Basic break mode allows you to correct the problem before you continue. Now you have to formally declare the slsPrice variable.

5. Enter the declaration statement

Dim slsPrice As Currency on a new line just below Sub CalcCost() and press F5 to continue. When you declare the slsPrice variable and rerun your procedure, Visual Basic will generate the same Compile error as soon as it encounters another variable name that was not declared. To fix the remaining problems in this

Introduction to Access 2003 VBA Programming procedure with the variable declaration, choose Run | Reset to exit the break mode.

6. Enter the following declarations at the beginning of the CalcCost procedure:

' declaration of variables Dim slsPrice As Currency Dim slsTax As Single Dim cost As Currency Dim strMsg As String

7. To run the procedure, click any line between the Sub and End Sub keywords and press F5 or choose Run | Run Sub/UserForm. Your revised CalcCost procedure looks like this:

MsgBox strMsg End Sub

The Option Explicit statement you entered at the top of the module (see step 2) forced you to declare variables. Because you must include the Option Explicit statement in each module where you want to require variable declaration, you can have Visual Basic enter this statement for you each time you insert a new module.

To automatically include Option Explicit in every new module you create, follow these steps:

3. Choose OK to close the Options window.

From now on, every new module will be added with the Option Explicit statement in line 1. If you want to require variables to be explicitly declared in a module you created prior to setting the Require Variable Declaration in the Options window, you must enter the Option Explicit statement manually by editing the module yourself.