Keyword

Exit


Description

The Exit statement causes control to Exit a loop and jump to another line of code without the loop conditions being satisfied. The optional keywords enable you to control where execution will resume.

Usage

Exit [ For | Do | While ]

or

Exit [ For loopVariable]

or

Exit [ Sub | Function ]

Part

Type

Description

LoopVariable

Datatype of a loop variable: Integer, Single, or Double.

The loop variable that controls iteration of the For statement that you want to exit.

Notes

If you use Exit without any optional keywords, whatever loop the Exit statement is in is exited.

If you use Exit with the Do keyword, the Do loop it is in, even if it is also inside another type of loop, is exited.

If you use Exit with the While keyword, the While loop it is in, even if it is also inside another type of loop, is exited.

If you use Exit with the For keyword without passing a parameter, it exits the innermost For loop it is in, even if it is also inside another loop.

If you have nested For statements, you can pass the For keyword the variable that controls the loop you want to Exit. For example, if you are testing all the elements of a two-dimensional array with nested For statements, you can use the loop variable for the outermost loop to Exit at that point.

For i = 0 To 255
  For j = 0 To 255
    If myArray(i, j) = 23 Then
      Exit For i
    End If
  Next
Next

If you use Exit with the Sub or Function keywords, then it will Exit the entire method or function as if you used Return. Exit Function cannot specify a return value, so if you use it to Exit a function, the function will return the default value for the data type of the function.

Sample code

This example searches a ListBox for a value in the first column, highlighting the first row that is found and exiting the loop:

Var searchString As String = "text to find"

For Each row As List
For i As Integer = 0 To ListBox1.LastRowIndex
  If ListBox1.CellTextAt(i, 0) = searchString Then
    ListBox1.SelectedRowIndex(i) = True
    Exit
  End If
Next

This is an example of a function that determines if the font named passed is installed on the user's computer. It uses Exit to get out of the loop when it finds the font that it was looking for.

Function FontAvailable(FontName As String) As Boolean
  Var fc As Integer
  fc = FontCount - 1

  Var fontFound As Boolean = False

  For i As Integer = 0 To fc
    If Font(i) = FontName Then
      fontFound = True
      Exit
    End If
  Next

  Return fontFound
End Function

Compatibility

All project types on all supported operating systems.

See also

Continue, Do...Loop, For...Next, GoTo, Return, While...Wend statements.