See Also Example
Exits a Do...Loop, a For...Next loop, a Function procedure
Syntax
Exit { Do | For | Function | Sub }
Remarks
You can use the Exit statement in any of the following ways:
Statement Description
Exit Do Provides a way to exit a Do...Loop statement. It can be used only inside a Do...Loop statement. Exit Do transfers control to the statement following the Loop statement. When used within nested Do...Loop statements, Exit Do transfers control to the loop that is one nested level above the loop in which it occurs.
Exit For Provides a way to exit a For...Next loop. It can be used only in a For...Next loop. Exit For transfers control to the statement following the Next statement. When used within nested For...Next loops, Exit For transfers control to the loop that is one nested level above the loop in which it occurs.
Exit Function Immediately exits the Function procedure in which it appears. Program execution continues with the statement following the statement that has called the Function.
Exit Sub Immediately exits the Sub procedure in which it appears. Program execution continues with the statement following the statement that has called the Sub.
Do not confuse Exit statements with End statements. Exit does not define the end of a structure.
Do...Loop Statement
End Statement
For...Next Statement
Function Statement
Stop Statement
Sub Statement
The example uses the Exit statement to exit a For...Next loop, a Do...Loop, and a Sub procedure. To try this example, paste the code into the Declarations section of a form. Then press F5 and click the form.
Sub Form_Click ()
Dim I, Num ' Declare variables.
Do ' Set up infinite loop.
For I = 1 To 1000
Num = Int(Rnd * 100) ' Generate random numbers.
Select Case Num ' Evaluate random number.
Case 7 : Exit For ' If 7, exit For...Next.
Case 29 : Exit Do ' If 29, exit Do...Loop.
Case 54 : Exit Sub ' If 54, exit Sub procedure.
End Select
Next I
Loop
End Sub