Access VBA Macro Programming

(Joao Candeias) #1

Again, a variable,x, is set to 0. The condition thatxmust be less than 50 is supplied, and
xis 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 ofxat 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 anExit Forstatement in a For..Next loop or a For Each loop. Use
anExit Dowithin aDo Untilloop. 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 anotherExitstatement in. The statementExit
DoandExit Forwill stop execution of the loop and go on to the next instruction after the
end of that loop.


Chapter 4: Programming Basics: Decisions and Looping 43

Free download pdf