Exiting a Control Structure

The Exit statement allows you to exit directly from a For loop, Do loop, Sub procedure, or Function procedure. The syntax for the Exit statement is simple: Exit For can appear as many times as needed inside a For loop, and Exit Do can appear as many times as needed inside a Do loop:

For counter = start To end [Step increment]
[statementblock]
[Exit For]

[statementblock]
Next [counter[, counter] [,...]]


Do [{While | Until} condition]
[statementblock]
[Exit Do]


[statementblock]
Loop

The Exit Do statement works with all versions of the Do loop syntax.

Exit For and Exit Do are useful because sometimes it’s appropriate to quit a loop immediately, without performing any further iterations or statements within the loop. For example, in the previous example that printed the fonts common to both the Screen and Printer, the code continues to compare Printer fonts against a given Screen font even when a match has already been found with an earlier Printer font. A more efficient version of the function would exit the loop as soon as a match is found:

Private Sub Form_Click()

Dim SFont, PFont

For Each SFont In Screen.Fonts()

For Each PFont In Printer.Fonts()

If SFont = PFont Then

Print Sfont

Exit For ' Exit inner loop.

End If

Next PFont

Next SFont

End Sub

As this example illustrates, an Exit statement almost always appears inside an If statement or Select Case statement nested inside the loop.

When you use an Exit statement to break out of a loop, the value of the control variable differs, depending on how you leave the loop:

Ø When you complete a loop, the control variable contains the value of the upper bound plus the step.

Ø When you exit a loop prematurely, the control variable retains its value subject to the usual rules on scope.

Ø When you iterate off the end of a collection, the control variable contains Nothing if it’s an Object data type, and contains Empty if it’s a Variant data type.

No comments:

Post a Comment