Finally, there is the While..Wend loop. This continues to loop while a specified condition is true. It stops as soon as the condition is false. The following is a simple example that is very similar to the previous Do Until loop:
Sub test_do() x = 0 While x < 50 x = x + 1 Wend MsgBox x End Sub
Again, a variable, x, is set to 0. The condition that x must be less than 50 is supplied, and x is incremented by 1 each time the loop is run. When x=50, it is no longer less than 50, so a message box is displayed showing the value of x at 50.
Early Exit of Loops
Under some circumstances, you may want your procedure to exit a loop early before it has worked all the way through and satisfied its criteria. An example might be where you are searching for a particular string of characters within an array. You may have 25 instances of that string to look through, but once the procedure has found what it is looking for, there is no point in further looping until the final condition is met. You could have an array of several thousand records you are searching through, and much time could be wasted carrying on to the bitter end when the instance has already been found. In the case of a For..Next loop, the value of the index is also preserved, which means you can use it to locate where your condition was correct. Here is an example:
Sub test_exit() For x = 1 To 100 If x = 50 Then Exit For End If Next x MsgBox x End Sub
You exit a loop by using an Exit For statement in a For..Next loop or a For Each loop. Use an Exit Do within a Do Until loop. In the case of a For..Next loop, the value of the index is preserved. If the loops are nested, your code will only exit from the loop it is actually in. It will not exit from the outer loop unless you put another Exit statement in. The statement Exit Do and Exit For will stop execution of the loop and go on to the next instruction after the end of that loop.