VBA course · Lesson 10 of 33

Do loops: Do While, Do Until and Exit Do

Repeat code until a condition changes with Do While and Do Until, test at the top or bottom, stop runaway loops with Esc or Ctrl+Break and use Exit Do.

Beginner 13 min read

A For loop (For loops: For...Next and For Each) is perfect when you know in advance how many times to repeat: rows 2 to 500, the 12 months, every sheet. But many jobs are different. You want to keep going until something happens: until you reach an empty cell, until the running total passes a budget, until the user types a valid answer. For these situations VBA has the Do loop.

A Do loop repeats a block of code while a condition is true, or until a condition becomes true. There is no counter built in; the loop keeps going as long as the condition says so. That flexibility is useful, and it also introduces a new danger, the infinite loop, which we will deal with below.

Do While...Loop

The Do While form checks a condition at the top. If it is true, the body runs, then VBA goes back to the top and checks again. As soon as the condition is false, the loop ends.

VBA
Option Explicit

Sub CountCustomers()
    Dim r As Long
    Dim count As Long

    r = 2
    Do While Cells(r, "A").Value <> ""
        count = count + 1
        r = r + 1
    Loop

    MsgBox count & " customers found."
End Sub
Walk down column A until the first empty cell

The key line is r = r + 1. Without it, r stays at 2, the condition never changes, and the loop runs forever. With a Do loop you are responsible for moving towards the exit. This is the single most important habit to build.

Note also that if A2 is empty to begin with, the body never runs at all and the message says 0. Because the condition is tested before the first pass, a top-tested loop can run zero times.

Do Until...Loop

Do Until is the mirror image: it keeps looping until the condition becomes true. These two loops do exactly the same thing:

VBA
Option Explicit

Sub TwoWays()
    Dim r As Long

    r = 2
    Do While Cells(r, "A").Value <> ""
        r = r + 1
    Loop
    Debug.Print "While version stopped at row " & r

    r = 2
    Do Until Cells(r, "A").Value = ""
        r = r + 1
    Loop
    Debug.Print "Until version stopped at row " & r
End Sub
Two ways to write the same loop

Choose whichever reads more naturally. "Do until the cell is empty" sounds more like plain English than "do while the cell is not empty", and avoiding a negative in the condition reduces mistakes. Debug.Print writes to the Immediate window (Ctrl+G in the editor), which is handy for checking values without message boxes; Error handling and debugging in VBA covers it in detail.

Testing at the bottom: Do...Loop While / Until

You can also place the condition after Loop. Then the body always runs at least once before the condition is checked.

VBA
Option Explicit

Sub AskInvoiceNumber()
    Dim answer As String

    Do
        answer = InputBox("Enter the invoice number (for example INV-1042):")
    Loop Until answer Like "INV-####" Or answer = ""

    If answer = "" Then
        MsgBox "Cancelled."
    Else
        MsgBox "Looking up " & answer
    End If
End Sub
Ask for an invoice number until the user types one

Asking for input is the classic case for a bottom-tested loop: you must ask at least once before you can check the answer. The Like operator compares text against a pattern (# means any digit); it is explained in Operators and expressions in VBA. The answer = "" test lets the user escape by pressing Cancel, which makes InputBox return an empty string. More on that in Talking to the user: MsgBox and InputBox.

FormCondition checkedMinimum runsStops when
Do While cond ... LoopBefore each pass0cond is False
Do Until cond ... LoopBefore each pass0cond is True
Do ... Loop While condAfter each pass1cond is False
Do ... Loop Until condAfter each pass1cond is True

A practical example: filling until a budget is reached

This macro goes down a list of purchase requests in priority order and approves them until the remaining budget cannot cover the next one. You cannot know beforehand how many will fit, so a Do loop is natural.

ABCDEF
1RequestItemCostDecisionBudget10000
2PR-01Laptops4200Left
3PR-02Monitors2600
4PR-03Desk chairs1900
5PR-04Projector1800
6PR-05Software900

Before: requests sorted by priority, budget 10,000 in F1, F2 will show what is left

VBA
Option Explicit

Sub ApproveWithinBudget()
    Dim remaining As Double
    Dim r As Long

    remaining = Range("F1").Value
    r = 2

    Do Until Cells(r, "A").Value = ""
        If Cells(r, "C").Value <= remaining Then
            Cells(r, "D").Value = "Approved"
            remaining = remaining - Cells(r, "C").Value
        Else
            Cells(r, "D").Value = "Rejected"
            Exit Do
        End If
        r = r + 1
    Loop

    Range("F2").Value = remaining
End Sub
Approve requests while the budget lasts
ABCDEF
1RequestItemCostDecisionBudget10000
2PR-01Laptops4200ApprovedLeft1300
3PR-02Monitors2600Approved
4PR-03Desk chairs1900Approved
5PR-04Projector1800Rejected
6PR-05Software900

After: three requests fit (8,700); the projector would exceed the 1,300 left, so the loop stops there

The loop has two exits. The normal one is the Until condition: an empty cell means the list is finished. The second is Exit Do, which leaves the loop immediately when a request does not fit, because the rule here is strict priority order. If instead you wanted to skip expensive items and keep checking cheaper ones, you would simply remove Exit Do.

Exit Do

Exit Do works like Exit For: it jumps straight to the line after Loop. It is often combined with a loop that has no condition at all (Do ... Loop), where the exit is decided somewhere in the middle of the body:

VBA
Option Explicit

Sub FindStaffMember()
    Dim r As Long
    Dim target As String

    target = "Kowalski"
    r = 2

    Do
        If Cells(r, "A").Value = "" Then
            MsgBox target & " is not on the staff list."
            Exit Do
        End If
        If Cells(r, "B").Value = target Then
            Cells(r, "B").Select
            MsgBox target & " found in row " & r
            Exit Do
        End If
        r = r + 1
    Loop
End Sub
Loop with the exit in the middle

This style is fine, but make sure every path eventually reaches an Exit Do. Here the empty-cell check guarantees the loop ends even if the name is missing.

Infinite loops and how to stop them

Sooner or later every VBA programmer writes a loop that never ends. Excel appears frozen, the cursor spins and nothing responds. Common causes are forgetting r = r + 1, testing the wrong column (one that never becomes empty), or a condition that can never be met, such as Do Until total = 1000 when the total jumps from 990 to 1,015.

To break out:

  • Press Esc, or Ctrl+Break on Windows. On laptops without a Break key try Ctrl+Fn+B or Ctrl+Fn+Pause, depending on the model. On a Mac press Cmd+. (Cmd and the full stop) or Esc.
  • A dialog appears: "Code execution has been interrupted". Click Debug to see the line where it stopped, or End to stop completely.
  • If Excel does not react at all, the last resort is closing it from the Task Manager (Mac: Force Quit), which loses unsaved work.
Watch out. Save your workbook before running a new loop for the first time. An infinite loop that writes to cells can also fill thousands of rows before you stop it.

Two defensive habits help. First, use >= or <= instead of = in numeric stop conditions, so overshooting still ends the loop. Second, add a safety counter during development:

VBA
Option Explicit

Sub SafeLoop()
    Dim total As Double
    Dim r As Long
    Dim guard As Long

    r = 2
    Do Until total >= 50000
        total = total + Cells(r, "C").Value
        r = r + 1
        guard = guard + 1
        If guard > 100000 Then
            MsgBox "Stopped: too many iterations, check the data."
            Exit Do
        End If
    Loop

    MsgBox "Target reached at row " & r - 1
End Sub
A safety limit while testing

While...Wend

You may see While ... Wend in older code. It behaves like Do While ... Loop, but it has no Exit statement and no bottom-tested version. It still works, but there is no reason to use it in new code; Do While does everything it does and more.

Common mistakes

  • No progress towards the exit: forgetting to increase the row counter or read new data.
  • Checking the wrong column for the end: if column A has gaps, a loop that stops at the first blank stops too early. Find the last row instead, as shown in Find the last row and build dynamic ranges in VBA.
  • Using = with decimals: floating-point values rarely hit an exact target.
  • Putting the condition in the wrong place: use the bottom-tested form when the body must run at least once.
  • Expecting a Do loop to count for you: unlike For, nothing increases automatically.

Check yourself

1. What is the minimum number of times a Do ... Loop Until body runs?

2. A Do While loop over rows never ends. What is the most likely cause?

3. Which key combination interrupts a running macro on Windows?

4. Which line is equivalent to Do While Cells(r, 1).Value <> ""?

5. Why use Do Until total >= 1000 instead of Do Until total = 1000?