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

Exit Statement

Syntax

Exit Do
Exit For
Exit Function
Exit Property
Exit Sub

Description

Prematurely exits a block of code.

Rules at a Glance

Exit Do

Exits a Do...Loop statement. If the current Do...Loop is within a nested Do...Loop, execution continues with the next Loop statement wrapped around the current one. If, however, the Do...Loop is standalone, program execution continues with the first line of code after the Loop statement.

Exit For

Exits a For...Next loop. If the current For...Next is within a nested For...Next loop, execution continues with the next Next statement wrapped around the current one. If, however, the For...Next loop is standalone, program execution continues with the first line of code after the Next statement.

Exit Function

Exits the current function.

Exit Property

Exits the current property procedure.

Exit Sub

Exits the current sub procedure.

Programming Tips and Gotchas

  • Traditional programming theory recommends one entry point and one exit point for each procedure. However, you can improve the readability of long routines by using the Exit statement. Using Exit Sub can save having to wrap almost an entire subroutine (which could be tens of lines long) within an If...Then statement.

    With Exit Sub:

    Sub MyTestSub(iNumber)
        If iNumber = 10 Then
            Exit Sub
        End If
        ...'code
    End Sub

    Without Exit Sub:

    Sub MyTestSub(iNumber)
        If iNumber <> 10 Then
            ...'code
        End If
    End Sub
  • In the case of the Exit Function, Exit Property, and Exit Sub statements, the point in the program to which program ...

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