DoUntil loop

The Do-Until loop structure is similar to the Do-While structure. The two structures differ in their handling of the tested condition. A program continues to execute a Do-While loop while the condition remains true. In a Do-Until loop, the program executes the loop until the condition is true.

Here's the Do-Until syntax:

Do [Until condition] statements] [Exit Do] [statements]

The following example is the same one presented for the Do-While loop but recoded to use a Do-Until loop:

Sub DoUntilDemo()

Do Until IsEmpty (ActiveCell.Value)

ActiveCell.Value = ActiveCell.Value * 2 ActiveCell.Offseta, 0).Select

Loop End Sub

You may encounter a different form of the Do-Until loop — a Do-Loop Until loop. The following example, which has the same effect as the preceding procedure, demonstrates an alternate syntax for this type of loop:

Sub DoLoopUntilDemo() Do

ActiveCell.Value = ActiveCell.Value * 2 ActiveCell.Offseta, 0).Select Loop Until IsEmpty (ActiveCell.Value) End Sub

There is a subtle difference in how the Do-Until loop and the Do-Loop Until loop operate. In the former, the test is performed at the beginning of the loop, before anything in the body of the loop is executed. This means that it is possible that the code in the loop body will not be executed if the test condition is met. In the latter version, the condition is tested at the end of the loop. This means, at a minimum, the Do-Loop Until loop always results in the body of the loop being executed once.

Was this article helpful?

0 0


Post a comment