Exiting Loops Early

Sometimes you may not want to wait until the loop ends on its own. It's possible that a user will enter the wrong data, a procedure will encounter an error, or perhaps the task has been completed and there's no need to do additional looping. You can leave the loop early without reaching the condition that normally terminates it. Visual Basic has two types of Exit statements:

The Exit For statement is used to end either a For.. .Next or a For Each.. .Next loop early.

The Exit Do statement immediately exits any of the VBA Do loops.

The following hands-on demonstrates how to use the Exit For statement to leave the For Each.. .Next loop early.

0 0

Post a comment