VBA Do Loop


Just like the For Next statement, the Do Loop statement is a code repetition instruction.

Usually the Do Loop statement is used when it is known that the loop has an end, but it is not known exactly when it will occur or what it is.

There are two types of Do loop in VBA: Do While and Do Until.


Do While

In the structure of this loop type, While is the instruction that specifies its end condition (without While the code would run indefinitely).

    X = 0
    Do While X < 3

        X = X + 1
        Msgbox X

    Loop

Note that it is similar to the If Then Else condition, if the evaluation of X < 3 is True. If so, the loop continues.

The While condition can be inserted both at the beginning (as shown above) or at the end (as shown below).

    X = 0
    Do

        X = X + 1
        Msgbox X

    Loop While X < 3

Note that in this second case you are guaranteed to run the code at least once. This occurs because the While output condition is at the end, so the input in the loop is unrestricted.


Do Until

The Until statement is used similarly to While, but its condition for execution is False, while for While is True.

Do While Version

    X = 0
    Do While X < 3

        X = X + 1
        Msgbox X

    Loop

Do Until Version

    X = 0
    Do Until X >= 3

        X = X + 1
        Msgbox X

    Loop

Notice how the same results are obtained both using conditional: Do Loop as Do While.


Leaving the Loop Ahead of Time

Sometimes we need VBA to exit the loop ahead of time. Usually this is done by using the conditional If...Then followed by the instruction Exit Do.

    X = 0
    Do Until X > 3

        If X = 0 Then
            Exit Do
        End If

        X = X + 1
        Msgbox X 'This Msgbox will not appear
    Loop

The same concept is used for loops For Next, with the Exit For statement.



Consolidating Your Learning

Suggested Exercises

Do Loop Sum Final Score


SuperExcelVBA.com is learning website. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. All Rights Reserved.

Excel ® is a registered trademark of the Microsoft Corporation.

© 2024 SuperExcelVBA | ABOUT

Protected by Copyscape