Option Explicit Statement (Visual Basic) 

Forces explicit declaration of all variables in a file.

Option Explicit { On | Off }

Parts

  • On
    Optional. Enables Option Explicit checking. If On or Off is not specified, the default is On.
  • Off
    Optional. Disables Option Explicit checking.

Remarks

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.

Note

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)

  1. On the Tools menu, choose Options.

  2. Open the Projects and Solutions node.

  3. Choose VB Defaults.

  4. Modify the Option Explicit setting.

To set Option Explicit on the command line

Example

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.

' Force explicit variable declaration.
Option Explicit On
Dim thisVar As Integer
thisVar = 10
' The following assignment produces a COMPILER ERROR because
' the variable is not declared and Option Explicit is On.
thisInt = 10 ' causes ERROR

See Also

Reference

Dim Statement (Visual Basic)
ReDim Statement (Visual Basic)
Option Compare Statement
Option Strict Statement
/optioncompare
/optionexplicit
/optionstrict
Visual Basic Defaults, Projects, Options Dialog Box