Option Explicit Statement (Visual Basic)

Forces explicit declaration of all variables in a file, or allows implicit declarations of variables.

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

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.

Note

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

  1. In Solution Explorer, select a project. On the Project menu, click Properties. For more information, see Introduction to the Project Designer.

  2. Click the Compile tab.

  3. 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

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