O'Reilly logo

VBScript in a Nutshell, 2nd Edition by Ron Petrusha, Matt Childs, Paul Lomax

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 Option Explicit statement must appear in a script before any other statements; otherwise, a nontrappable error occurs.

  • In modules where the Option Explicit statement isn’t used, any undeclared variables are declared automatically.

  • Where Option Explicit is used, all variables must be declared using the Dim, Private, Public, or ReDim statements.

Programming Tips and Gotchas

  • It’s considered good programming practice to always use the Option vbCrLfExplicit statement. The following example shows why:

        Dim iVariable
        
        iVariable = 100
        iVariable = iVarable + 50
        MsgBox iVariable

    In 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 because iVarable is assumed to be an undeclared variant whose value is 0. If the Option Explicit statement had been used, the code wouldn’t have executed without generating an error, and iVarable would have been highlighted as the cause when Error 500, “Variable is undefined,” was raised.

  • For ASP pages, the Option Explicit statement must appear before the beginning of the HTML stream. For example:

    <% Option Explicit %>
    <HTML>

    A single Option Explicit statement applies to all script blocks in an ASP page.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required