Perform Multiple Tasks Until A Condition Is

You can execute a task or a series of tasks until a specific condition is met by using the Do Until loop statement in VBA. A Do Until loop provides a great means for repeating a series of statements. For example, a Do Until loop lets you apply changes to a series of cells until you encounter an empty cell.

When you use the Do Until loop, the statements you specify between the Do and Loop statements execute until the specified condition is met. As soon as the looping structure determines that the condition is true, control moves to the next statement outside the loop.

The Do Until loop consists of four basic parts. The Do statement initiates the loop. The Until condition statement typically follows the Do statement, although you can also specify the Until condition at the end of the loop.

PERFORM MULTIPLE TASKS UNTIL A CONDITION IS MET

The body of the loop contains a series of statements that perform until the value of the statement meets the condition of the loop . Finally, the Loop statement marks the end of the loop.

When the Until condition follows the Do statement, the Do Until loop checks to see if the condition is true before executing. If the condition is not true, the loop executes. With this form of the Do Until loop, the loop may never execute if the statement meets the condition of the loop before the loop executes the first time.

When you place the Until condition at the end of the loop, the Do Until loop always executes once and then checks the condition. If the condition is true at that point, the Do Until loop stops execution, and control passes to the next VBA statement in your macro.

PERFORM MULTIPLE TASKS UNTIL A CONDITION IS MET

—B Type Dim N As Integer, replacing N with the name of the variable to increment in the loop.

^0 Initialize the value of the variable.

—B Type Dim N As Integer, replacing N with the name of the variable to increment in the loop.

^0 Initialize the value of the variable.

^0 Type the Until condition, followed by the condition of the loop.

■ Alternately, you can skip step 5 and perform steps 6 through 9 to place the Until condition at the end of the loop.

■ In this example, the loop repeats until it encounters an empty cell.

0 0

Post a comment