Requiring Explicit Variable Declarations

To avoid the problem of inadvertently creating new variables by misspelling the names of existing variables, you can stipulate that Visual Basic generate an error message whenever it encounters a name used as a variable but not previously declared explicitly as a variable. To require explicit variable declarations, place the following statement at the top of each module in which you want Visual Basic to enforce explicit declarations.


Option Explicit

You must manually add this line to the top of each existing module in which you want this option to be turned on, but you can have Visual Basic automatically add the line to new modules.

To have Visual Basic automatically add the Option Explicit statement to new modules

With Option Explicit in effect for the module containing the SwapCells procedure, Visual Basic requires that variables be declared before you can use them. The following example shows the procedure with the added variable declaration.


Sub SwapCells()
    Dim tempVal
    With Worksheets(1)
        tempVal = .Range("a1").Value
        .Range("a1").Value = .Range("a2").Value
        .Range("a2").Value = temVal
    End With
End Sub

When you try to run this procedure, Visual Basic generates an error message telling you that the temVal variable is undeclared. Recognizing that this error means you've misspelled the variable name, you can fix the name before it causes the procedure to fail.

Tip

Because the Option Explicit statement helps you catch errors in variable names, and because it encourages you to use explicit data types, you should use it all the time.