VBA Do Until Loop

The Do Until Loop is used when we want to repeat a block of code or a set of statements indefinitely until the condition is True. The condition can be checked either at the start or at the end of the loop.

The Do Until … Loop Statements check the condition at the start of the loop and The Do … Loop Until Statements check the condition at the end of the loop.

If the condition is checked at the start of the loop, the block of code does not execute if the condition is met itself initially (and the loop does not run even once). And if the condition is checked at the end, the Loop runs atleast once.

Syntax

Do Until… loop statements

Flow Diagram

VBA Do Until Loop

Example

In this example, we use Do Until… loop to check the condition at the starting of the loop. The statement inside the loop is executed only if the condition is false. And it exists out of the loop when then the condition is True.

After executing the code, you will get the output:

The value of i is: 6    The value of i is: 7    The value of i is: 8    The value of i is: 9    The value of i is: 10    The value of i is: 11  

Do… Until loop statements

Do…Until loop is used to check the condition at the end of the loop.

Syntax

Flow Diagram

VBA Do Until Loop

Example

In this example, we use Do…Until loop to check the condition at the end of the loop. The statements inside the loop are executed at least once, even if the condition is true.

After executing the code, you will get the following output in a message box.

VBA Do Until Loop

Exit Do Statement

You can exit the Do While or Do Until Loop early, without completing the full cycle, by using the Exit Do statement.

The Exit Do statement will immediately stop the execution of the loop and execute the section of code immediately. In the case of the inner nested level, it will stop and executes the next outer nested level.

You can have multiple numbers of Exit Do statements in a single loop. It is particularly useful in a case where you want to terminate the loop on reaching a particular value or satisfying a specific condition, or in case you want to end an endless loop at a certain point.

For example:

Executes the above code and you will get the following output.

VBA Do Until Loop


Next TopicVBA Functions