Name
Option Explicit Statement
Syntax
Option Explicit
Description
Use Option
Explicit to generate
an error whenever a variable that has not been declared is
encountered.
Rules at a Glance
The
OptionExplicitstatement must appear in a script before any other statements; otherwise, a nontrappable error occurs.In modules where the
OptionExplicitstatement isn’t used, any undeclared variables are automatically cast as variants.Where
OptionExplicitis used, all variables must be declared using theDim,Private,Public, orReDimstatements.
Programming Tips & Gotchas
It’s considered good programming practice to always use the
OptionExplicitstatement. The following example shows why:Dim iVariable iVariable = 100 iVariable = iVarable + 50 MsgBox iVariableIn this code snippet, a variable
iVariable, has been declared. However, because the name of the variable has been mistyped in line 3, the message box shows its value as 50 instead of 150. This is becauseiVarableis assumed to be an undeclared variant whose value is 0. If theOptionExplicitstatement had been used, the code wouldn’t have executed without generating an error, andiVarablewould have been highlighted as the cause when Error 500, “Variable is undefined,” was raised.For ASP pages, the
Option Explicitstatement must appear before the beginning of the HTML stream. For example:<% Option Explicit %> <HTML>
A single
OptionExplicitstatement applies to all script blocks in an ASP page.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access