6.8. Using the Exit Statement in Repetition StatementsThe Exit statement can be used to alter a program's flow of control. There are many forms of the Exit statement, designed to exit different types of code blocks. In this section, we focus on using the Exit statement in repetition statements. The Exit Do statement can be executed in a Do While...Loop, Do...Loop While, Do Until...Loop or Do...Loop Until statement, to cause the program to exit immediately from that repetition statement. Similarly, the Exit For statement and the Exit While statement cause immediate exit from For...Next and While...End While loops, respectively. Execution continues with the first statement after the repetition statement. Figure 6.15 demonstrates the Exit For, Exit Do and Exit While statements in their respective repetition statements. Figure 6.15. Exit statement in repetition statements.
The header of the For...Next statement (line 8) indicates that the body of the loop is to execute 10 times. During each execution, the If...Then statement (lines 1012) determines whether the control variable, counter, is equal to 5. For the first four iterations of the loop (counter values 14), this condition is false, so program control proceeds to line 14, which displays the current value of counter. Once the value of counter reaches 5, the condition in line 10 evaluates to true, so the Exit For statement (line 11) executes, terminating the execution of the loop. Program control then proceeds to the output statement in lines 1718, which displays the value of counter after the loop has been exited. Line 19 resets the value of counter for the next repetition statement. The header of the Do Until...Loop statement (line 22) indicates that the loop should continue executing until counter is greater than 10. When counter has values in the range 14, the body of the If...Then statement (lines 2426) is skipped, the current value of counter is displayed (line 28) and counter is incremented (line 29). However, when counter is 5, the Exit Do statement (line 25) executes, terminating the loop. Lines 3233 display the value of counter after the loop has been exited. Note that the program does not increment counter (line 29) after the Exit Do statement executes. Line 34 once again resets the value of counter for the next repetition statement. The header of the While statement (lines 37) indicates that the loop should continue executing while counter is less than or equal to 10. When counter is 5, the Exit While statement (line 40) executes, terminating execution of the While statement. Lines 4748 display the value of counter after the loop has been exited. The Exit Select statement can be used to exit a Select...Case statement. The Exit Property statement can be used to exit from a property. We encounter different forms of the Exit statement throughout the book. |