Option Explicit Statement
Description
Used at module level to force explicit declaration of all variables in that module.
Syntax
Option Explicit
Remarks
If used, the Option Explicit statement must appear in a module before any procedures.
When Option Explicit appears in a module, you must explicitly declare all variables using the Dim, Private, Public, ReDim, or Static 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 Variant type unless the default type is otherwise specified with a Deftype statement.
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.
See Also
Const statement, Deftype statements, Dim statement, Function statement, Option Base statement, Option Compare statement, Option Private statement, Private statement, Public statement, ReDim statement, Static statement, Sub statement.
Specifics (Microsoft Access)
In Microsoft Access, you can ensure that all new modules will automatically include the Option Explicit statement. Click Options on the Tool menu, click the Module tab, and select the Require Variable Declaration option.
Once you select this option, it will automatically be set for all other databases which you create or open with Microsoft Access.
Note When you select this option, only new modules will have the Option Explicit setting. You must enter the Option Explicit statement into the Declarations section of any existing modules. Or, when the module is open, click Options on the Tools menu, click the Module tab, and select the Require Variable Declaration option.
Example
This example uses the Option Explicit statement to force you to explicitly declare 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 ' Force explicit variable declaration.
Dim MyVar ' Declare variable.
MyInt = 10 ' Undeclared variable generates error.
MyVar = 10 ' Declared variable does not generate error.