Sometimes you may find situations in which you will want to break out of a loop before it finishes processing, based on some condition that occurs. To deal with this type of situation, you can use either of two types of Exit statements to force an immediate termination of a loop. Once executed, the Exit statement transfers control to the next statement following the loop within the application.
You can use the Exit statement to break out of any For…Next or For Each…Next loop. The syntax for this form of the Exit statement is shown below.
Exit For
The following example demonstrates how to use the Exit For statement to break out of the processing of a loop.
Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim intCounter As Integer Dim strResponce As String Dim UserArray(4) As String For intCounter = 0 To 4 strResponce = InputBox("Enter a name or type Quit to exit.") If strResponce.ToLower = "quit" Then MessageBox.Show("Data collection has been terminated.") Exit For End If UserArray(intCounter) = strResponce Next End Sub
In this example, a For…Next loop has been set up to collect five names that the user supplies by entering them into a pop-up window generated by an InputBox() function. However, if at any point during the collection process the user decides to enter the word "Quit," the Exit For statement executes and terminates the data collection process.
You can also use the Exit statement to break out of any Do…Until or Do…While loop. The syntax for this form of the Exit statement is shown below.
Exit Do
The following example demonstrates how to use the Exit Do statement to break out of the processing of a loop.
Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim intCounter As Integer = 0 Dim intOverFlow As Integer = 50 Dim strResponce As String ="" Dim blnTerminate As Boolean = False Dim UserArray(49) As String Do Until blnTerminate = True strResponce = InputBox("Enter a name or type Quit to exit.") If strResponce.ToLower = "quit" Then MessageBox.Show("Data collection has been terminated.") blnTerminate = True Else UserArray(intCounter) = strResponce intCounter += 1 If intCounter = intOverFlow Then MessageBox.Show("Error: Array overflow, max size = 50") Exit Do End If End If Loop End Sub