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.
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.
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 SubThe 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:
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 SubChoose 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.
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 SubAsking 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.
| Form | Condition checked | Minimum runs | Stops when |
|---|---|---|---|
| Do While cond ... Loop | Before each pass | 0 | cond is False |
| Do Until cond ... Loop | Before each pass | 0 | cond is True |
| Do ... Loop While cond | After each pass | 1 | cond is False |
| Do ... Loop Until cond | After each pass | 1 | cond 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.
| A | B | C | D | E | F | |
|---|---|---|---|---|---|---|
| 1 | Request | Item | Cost | Decision | Budget | 10000 |
| 2 | PR-01 | Laptops | 4200 | Left | ||
| 3 | PR-02 | Monitors | 2600 | |||
| 4 | PR-03 | Desk chairs | 1900 | |||
| 5 | PR-04 | Projector | 1800 | |||
| 6 | PR-05 | Software | 900 |
Before: requests sorted by priority, budget 10,000 in F1, F2 will show what is left
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| A | B | C | D | E | F | |
|---|---|---|---|---|---|---|
| 1 | Request | Item | Cost | Decision | Budget | 10000 |
| 2 | PR-01 | Laptops | 4200 | Approved | Left | 1300 |
| 3 | PR-02 | Monitors | 2600 | Approved | ||
| 4 | PR-03 | Desk chairs | 1900 | Approved | ||
| 5 | PR-04 | Projector | 1800 | Rejected | ||
| 6 | PR-05 | Software | 900 |
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:
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 SubThis 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.
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:
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 SubWhile...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?
When the condition is at the bottom, the body runs once before it is checked.
2. A Do While loop over rows never ends. What is the most likely cause?
Without r = r + 1 (or similar), the condition never changes.
3. Which key combination interrupts a running macro on Windows?
Esc or Ctrl+Break interrupts the code and offers Debug or End.
4. Which line is equivalent to Do While Cells(r, 1).Value <> ""?
"While not empty" and "until empty" are the same condition expressed the other way round.
5. Why use Do Until total >= 1000 instead of Do Until total = 1000?
Range comparisons still stop the loop when the value overshoots the target.