CATCHING MISSPELLED VARIABLE NAMES


The VBA compiler doesnt care about the capitalization style of your variable names. MyVar, myVar, and myvar are identical names as far as the compiler is concerned. (If youre inconsistent about the capitalization of a variable name, the VBE adjusts all instances of that variable to make them look the same.)

If you change the spelling of a variable name in mid-program, however, the compiler creates a new variableand havoc for your program. An error in programming introduced by a misspelled variable can be especially treacherous because the program might appear to behave normally.

You can virtually eliminate the possibility of inconsistently spelled variable names in a module by adding a single statement at the top of that module (above any Sub or Function statements):

    Option Explicit
The Option Explicit statement forces you to declare any variables used in the current module. You declare variables with Dim statements. (For the complete details about Dim, type Dim in a module and press F1.) With Option Explicit in place, if you use a variable without first declaring it, you get a Compile Error at run time. If you accidentally misspell a variable name somewhere in your program, the misspelled variable will be flagged by the compiler as an undeclared variable, and you will be able to fix the problem forthwith.

You can add Option Explicit to every new module you create by choosing Tools, Options, clicking the Editor tab, and selecting Require Variable Declaration. This option is off by default, but itfs good programming practice to turn it on. Option Explicit will do more for you than eliminate misspelled variable names. By forcing you to declare your variables, it will also encourage you to think ahead as you work.