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 currentDo...Loop
is within a nestedDo...Loop
, execution continues with the nextLoop
statement wrapped around the current one. If, however, theDo...Loop
is standalone, program execution continues with the first line of code after theLoop
statement.Exit
For
Exits a
For...Next
loop. If the currentFor...Next
is within a nestedFor...Next
loop, execution continues with the nextNext
statement wrapped around the current one. If, however, theFor...Next
loop is standalone, program execution continues with the first line of code after theNext
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. UsingExit
Sub
can save having to wrap almost an entire subroutine (which could be tens of lines long) within anIf...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
, andExit
Sub
statements, the point in the program to which program ...
Get VBScript in a Nutshell, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.