|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
Option Explicit Statement (Visual Basic)
Forces explicit declaration of all variables in a file.
If used, the Option Explicit statement must appear in a file before any other source code statements.
When Option Explicit appears in a file, you must explicitly declare all variables using the Dim or ReDim statements. If you attempt to use an undeclared variable name, an error occurs at compile time.
Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid confusion in code where the scope of the variable is not clear. If you do not use the Option Explicit statement, all undeclared variables are of Object type.
The compiler default is Option Explicit On if you do not specify Option Explicit in your code.
You can also set Option Explicit in the Visual Studio integrated development environment (IDE) or on a command line.
To set Option Explicit in the integrated development environment (IDE)
On the Tools menu, choose Options.
Open the Projects and Solutions node.
Choose VB Defaults.
Modify the Option Explicit setting.
To set Option Explicit on the command line
Include thecompiler 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.