Visual Basic Language Reference  

Option Explicit Statement

Used at file level to force explicit declaration of all variables in that file.

Option Explicit { On | Off }

Parts

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

Remarks

If used, the Option Explicit statement must appear in a file before any other source statements.

When Option Explicit appears in a file, you must explicitly declare all variables using the Dim, Private, Public, or ReDim statements. If you attempt to use an undeclared variable name, an error occurs at compile time.

If you don't use the Option Explicit statement, all undeclared variables are of Object type.

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

Example

This 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. The Option Explicit statement is used at the module level only.

Option Explicit On   ' Force explicit variable declaration.
Dim MyVar As Integer   ' Declare variable.
MyInt = 10   ' Undeclared variable generates error.
MyVar = 10   ' Declared variable does not generate error.

See Also

Const Statement | Dim Statement | Function Statement | Option Compare Statement | Private | Public | ReDim Statement | Sub Statement | /optionexplicit | /optionstrict | /optioncompare:binary | /optioncompare:text