Option Explicit Statement in VBA

Q. How to avoid incorrectly typing the name of an existing variable?

A. Use Option Explicit statement at file level to force explicit declaration of all variables in the script:

Option Explicit

Option Explicit statement must appear in a script before any procedures.

When you use the Option Explicit statement, 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:

Dim myVar
myVar = 1
myNewVar = 0	' ERROR: Variable not defined.


comments powered by Disqus