Option Explicit Statement
See Also Example
Forces explicit declaration of all variables.
The Option Explicit statement is used in the Declarations section of a form or module to force explicit declaration of all variables for that form or module.
If you don't use the Option Explicit statement, all undeclared variables are of Variant When you use the Option Explicit statement, all variables must be explicitly declared before they are used in Dim, Global, ReDim, or Static statements . If you attempt to use an undeclared variable name, a data type (unless the default type is otherwise specified with a Deftype statement).Variable not declared error occurs at compile time.
Tip Use Option Explicit to avoid mistyping the name of an existing variable or to avoid risking confusion in code in which the scope of the variable is not clear.
Note You can automatically include an Option Explicit statement in your code by selecting the Environment menu item from the Options menu and changing the Require Variable Declaration option to Yes.
Option Explicit Statement Example
The example uses Option Explicit to force you to explicitly declare all variables. To try this example, paste the code into the Declarations section of a form. Then press F5. You'll immediately notice that because the variable X has not been formally declared using the Dim statement or equivalent, that the Variable not defined error message is displayed.
Option Explicit ' Force variable declaration.
Sub Form_Click ()
Print X ' Print X on form