Most programming languages, such as C and Fortran, require that you explicitly declare all variables before you use them. Visual Basic 6 does not—you can use a variable in code without declaring it. Some VB programmers tout this as an advantage of VB, but, in fact, it's a serious shortcoming. Here's why.
When a VB program does not explicitly declare variables (with a Dim, Private, or Public statement), VB creates a new variable in memory every time it encounters a new variable name in code. If you misspell a name, VB cannot know that it's an error; it just creates a new variable and initializes it, a process called implicit variable declaration. This can cause serious problems and make it difficult to find bugs in a program when, for example, a calculation uses a misspelled variable that was initialized to zero rather than the correct variable that you intended.
Another shortcoming is that such implicitly declared variables are always of type Variant, which denies you the program efficiencies that result from using the proper data type for your variables.
Fortunately, there is a way around this. If you include the Option Explicit statement in a module, then VB will require explicit declarations for all variables in that module. Any misspelled variables are flagged as syntax errors when you try to run the program, and then you can make the necessary corrections. Place the Option Explicit statement at the start of each module (before any procedures). You can make this automatic by selecting Tools | Options and, on the Editor tab, selecting the Require Variable Declaration option.
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!