Exit Statement

Immediately moves control out of a loop, procedure, or program.

Syntax

Exit structure_keywords
or
Exit Program [ exit_code ]

Parts

structure_keywords
one of the keywords for procedures: Function, Method, Property, or Sub.
Alternatively, one or more of the keywords for loops: Do, For, or While. You can write a comma between each keyword to make a list.
Exit Program
Immediately stops the Program module in which it is used. Program flow continues with the process that started the program.
exit_code
Optional integer value. The default value is zero (0).

Instructions

Exit Do immediately stops the Do...Loop loop in which it is used. Program flow continues with the line after Loop.

Exit For immediately stops the For...To or For Each...In loop in which it is used. Program flow continues with the line after End For.

Exit Function immediately stops the Function procedure in which it is used. Program flow goes back to the line that called the procedure, if there are more procedures to call. The procedure returns the value of the variable with the same name as the procedure.

Exit Method immediately stops the Method procedure in which it is used. Program flow goes back to the line that called the procedure, if there are more procedures to call. The procedure returns the value of the variable with the same name as the procedure.

Exit Property immediately stops the Property procedure in which it is used. Program flow goes back to the line that called the procedure, if there are more procedures to call. The procedure returns the value of the variable with the same name as the procedure.

Exit Sub immediately stops the Sub procedure in which it is used. Program flow continues on the line after the line that called the procedure.

Exit While immediately stops the While loop in which it is used. Program flow continues with the line after End While.

With nested structures

When Exit is used in nested structures of the same type (for example, two For loops), Exit breaks out of the most inner structure and gives control to the next higher level. If you need to break out of more than one level, you can write each structure's keyword in order, with a comma between each one. See the example below.

With Begin...When

You must be careful when you use Exit in a Begin...When structure. This structure lets you catch when a loop completes correctly. When Exit breaks out of a loop, When %Done and When Else are ignored.

Examples

Nested For loops

For i = 0 To 9
    For j = 0 To 9
        ' If element is zero, exit both loops.
        If array(i, j) = 0 Then Exit For, For
    End
End

See also