Option Explicit Statement (Visual Basic)
Forces explicit declaration of all variables in a file, or allows implicit declarations of variables.
When Option Explicit On or Option Explicit appears in a file, you must explicitly declare all variables by using the Dim or ReDim statements. If you try to use an undeclared variable name, an error occurs at compile time. The Option Explicit Off statement allows implicit declaration of variables.
If used, the Option Explicit statement must appear in a file before any other source code statements.
Setting Option Explicit to Off is generally not a good practice. You could misspell a variable name in one or more locations, which would cause unexpected results when the program is run.
When an Option Explicit Statement Is Not Present
If the source code does not contain an Option Explicit statement, the Option Explicit setting on the Compile Page, Project Designer (Visual Basic) is used. If the command-line compiler is used, the /optionexplicit compiler option is used.
To set Option Explicit in the IDE
In Solution Explorer, select a project. On the Project menu, click Properties. For more information, see Introduction to the Project Designer.
Click the Compile tab.
Set the value in the Option Explicit box.
When you create a new project, the Option Explicit setting on the Compile tab is set to the Option Explicit setting in the VB Defaults dialog box. To access the VB Defaults dialog box, on the Tools menu, click Options. In the Options dialog box, expand Projects and Solutions, and then click VB Defaults. The initial default setting in VB Defaults is On.
To set Option Explicit on the command line
Include the /optionexplicit compiler option in the vbc command.
The following example uses the Option Explicit statement to force explicit declaration of all variables. Attempting to use an undeclared variable causes an error at compile time.