Exit For ”Getting Out of a For Loop Early
Our program builds an array of names and phone numbers. In a more useful program, we might want to search this list later for the name and phone number of a particular individual. Indeed, searching lists of data is a common programming problem. At issue here, however, is how to we get out of the loop early? In other words, if we have a list of 200 names and numbers and we find the one we want at index 25, do we really have to plow through 175 additional entries we're not interested in? Clearly, the answer is no.
Consider the following code fragment for our list of 200 names:
For i = 0 to 200 If MyList(i).Name = PersonToFind Then Exit For End if Next I txtList.Text = MyList(i).Name & " " & MyList(i).Phone
In this For loop, we use an If statement to see whether we've found the person we're looking for. If so, the Exit For statement is executed. The Exit For statement sends program control outside of the For statement block to the statement immediately following the Next statement. In the code fragment, control would be sent to the assignment statement for txtList.Text (just after the Next statement). Therefore, you can use an Exit For to get out of the For statement block prior to reaching the terminating value of the loop counter.