Forcing Declaration of Variables

Visual Basic has the Option Explicit statement that automatically reminds you to formally declare all your variables. This statement has to be entered at the top of each of your modules. The Option Explicit statement will cause Visual Basic to generate an error message when you try to run a procedure that contains undeclared variables.

1. Return to the Code window where you entered the CalcCost procedure.

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

3. Run the CalcCost procedure. Visual Basic displays the error message "Compile error: Variable not defined."

4. Click OK to exit the message box.

Visual Basic highlights the name of the variable slsPrice. Now you have to formally declare this variable. When you declare the slsPrice variable and rerun your procedure, Visual Basic will generate the same error as soon as it encounters another variable name that was not declared.

5. 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

6. Press F5 to run the procedure. The revised CalcCost procedure is shown below:

Option Explicit

Sub CalcCost() 'declaration of variables Dim slsPrice As Currency Dim slsTax As Single Dim Cost As Currency Dim strMsg As String slsPrice = 35 slsTax = 0.085

Range("A1").Formula Range("A4").Formula Range("B4").Formula Range("A5").Formula Range("A6").Formula Range("B5").Formula

= "The cost of calculator" = "Price" = slsPrice = "Sales Tax" = "Cost"

Cost = Format(slsPrice + (slsPrice * slsTax), "0.00") With Range("B6").Fonriula = Cost strMsg = "The calculator total is " & "$" & Cost & "." Range("A8").Fonriula = strMsg End Sub

The Option Explicit statement entered at the top of the module forced you to declare variables. Because you must include the Option Explicit statement in each module for which 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:

1. Choose Tools | Options.

2. Make sure the Require Variable Declaration check box is selected in the Options dialog box (Editor tab).

3. Choose OK to close the Options dialog box.

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 previously created module, you must enter the Option Explicit statement manually by editing the module yourself.

0 0

Post a comment