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
ExitDoExits a
Do...Loopstatement. If the currentDo...Loopis within a nestedDo...Loop, execution continues with the nextLoopstatement wrapped around the current one. If, however, theDo...Loopis standalone, program execution continues with the first line of code after theLoopstatement.ExitForExits a
For...Nextloop. If the currentFor...Nextis within a nestedFor...Nextloop, execution continues with the nextNextstatement wrapped around the current one. If, however, theFor...Nextloop is standalone, program execution continues with the first line of code after theNextstatement.ExitFunctionExits the current function.
ExitPropertyExits the current property procedure.
ExitSubExits 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
Exitstatement. UsingExitSubcan save having to wrap almost an entire subroutine (which could be tens of lines long) within anIf...Thenstatement.With
Exit Sub:Sub MyTestSub(iNumber) If iNumber = 10 Then Exit Sub End If ...'code End SubWithout
Exit Sub:Sub MyTestSub(iNumber) If iNumber <> 10 Then ...'code End If End SubIn the case of the
ExitFunction,ExitProperty, andExitSubstatements, the point in the program to which program ...
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