VBA Do While and Do Until loops
Sometimes you cannot know in advance how often a loop has to run. A Do loop keeps going while a condition holds, or until it becomes true: down to the first empty row, until a target is reached. In return, it is up to you to make sure it stops.
In short: Do While condition … Loop repeats as long as the condition is true. Do Until condition … Loop repeats until it becomes true. Something inside the loop has to change, or it never ends.
What you need to know: For Next, For Each and conditions from If Then Else.
Try it right now
The attendee list needs numbering, as far down as names have been entered. The loop stops at the first empty cell in column B.
Task The attendee list for a training session needs a running number. The macro NumberRows should use Do While to write 1, 2, 3 and so on into column A for as long as there is a name in column B. Check tests with more attendees.
| A | B | C | D | |
|---|---|---|---|---|
| 1 | No. | Attendee | Company | |
| 2 | Laura Bennett | Kingston Utilities | ||
| 3 | Omar Haddad | Peters Motors | ||
| 4 | Rachel Stone | Riverside Dental | ||
| 5 | Kevin Walsh | Green Leaf Garden Centre | ||
| 6 | Megan Ross | Hotel Marlow | ||
| 7 | Luke Morgan | Carter Bakery |
How Do While works
Sub NumberRows()
Dim r As Long
r = 2
Do While Cells(r, 2).Value <> ""
Cells(r, 1).Value = r - 1
r = r + 1
Loop
End Sub
| Part | Meaning |
|---|---|
r = 2 | Start value. Unlike For, you set it yourself before the loop. |
Do While … <> "" | Checked before every pass: is there something in column B? Only then does the body run. |
r = r + 1 | Move down one row. In a For loop, Next does this; here you write it yourself. |
Loop | Back to Do to check again. |
<> "" means "is not empty". A cell that never held anything counts as empty in this comparison.
The four forms
| Form | Runs | Checks |
|---|---|---|
Do While x … Loop | while x is true | before each pass, so possibly not at all |
Do Until x … Loop | until x is true | before each pass |
Do … Loop While x | while x is true | after each pass, so at least once |
Do … Loop Until x | until x is true | after each pass, at least once |
While and Until mirror each other: Do While balance < target and Do Until balance >= target do the same job. Use whichever reads more naturally. Exit Do leaves the loop in the middle of a pass, typically inside an If.
Older code sometimes uses While … Wend. It works like Do While … Loop but has no Exit statement. For new code, Do is the better choice.
When to use Do instead of For
For fits when the number of passes is known before you start, such as row 2 down to the last row. Do fits when it only becomes clear along the way: how many years until savings with interest reach a target? You only know once you have worked it out.
balance = Range("B1").Value
Do Until balance >= Range("B3").Value
balance = balance * (1 + Range("B2").Value)
years = years + 1
Loop
Task A company is saving up for a new machine, and interest is added every year. The macro YearsToTarget should use Do Until to work out after how many years the savings in B1, growing at the rate in B2, reach or pass the target in B3, and write the number of years to B5.
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Savings today | 10,000.00 | ||
| 2 | Interest rate per year | 3.0% | ||
| 3 | Target | 12,000.00 | ||
| 4 | ||||
| 5 | Years to target |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Avoiding an infinite loop
A Do loop only ends when something in its body changes what the condition tests. Forget r = r + 1 and the loop checks the same cell over and over. If that cell has data, it runs forever. The exercises stop such a macro after a short time and report: "The macro did not finish, so a loop probably never ends. Does the condition change on every pass, for example with i = i + 1 or by moving to the next row?"
The second trap is a condition that can never become true. In the savings example, an interest rate of 0 in B2 means the balance never grows and the target is never reached. If you expect cases like that, add a safety net such as If years > 100 Then Exit Do, or check before the loop that the rate is above 0.
Task Find the bug: the macro AddExpenses should add up the amounts on the expense claim until it reaches an empty cell in column B, then write the total to E2. But it never finishes. Get it running.
| A | B | C | D | E | |
|---|---|---|---|---|---|
| 1 | Receipt | Amount | |||
| 2 | Taxi from station | 18.40 | Total | ||
| 3 | Hotel, 1 night | 96.00 | |||
| 4 | Train ticket | 54.90 | |||
| 5 | Parking | 12.00 | |||
| 6 | Client dinner | 67.30 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Common mistakes
Forgetting Loop
Without Loop at the end, VBA stops before the macro starts: "Compile error: Do without Loop". As with For, clean indentation helps: Do and Loop line up exactly.
Not moving the counter on
That is the infinite loop from the last exercise. In a For loop, Next counts up for you; in a Do loop, nothing does. Get into the habit of writing r = r + 1 just above Loop before you fill in the rest of the body.
Forgetting the start value
Without r = 2, the variable starts at 0. There is no Cells(0, 2), and the exercise reports "Run-time error '1004': Application-defined or object-defined error". In a For loop the For line sets the start value; with Do, you put it before the loop yourself.
Mixing up While and Until
Do Until Cells(r, 2).Value <> "" ends straight away, because the first cell is already not empty, so the macro changes nothing. Read the line out loud: "repeat until the cell is not empty" sounds wrong, "repeat while it is not empty" sounds right.
In real Excel
When a macro is stuck in an infinite loop, Excel seems to freeze. Esc or Ctrl+Break usually interrupts it, and Excel asks whether to end or debug. Debug jumps to the line the macro was on. Unsaved work is at risk in that situation, so save before you test a new macro for the first time.
Stepping through with F8 helps while testing: after every pass you see whether the counter changes. More in Debugging.
FAQ
Which is better, Do While or For with the last row?
For lists, usually For with the last row: it is guaranteed to end, and it does not stop at gaps. Do While up to the first empty cell stops at a gap. That can be what you want, for example when notes sit a few rows below the list.
Can a Do loop run without any condition?
Yes, Do … Loop without While or Until runs until an Exit Do inside it is reached. You rarely need it, and it easily becomes an infinite loop.
Why does the exercise stop my loop when Excel does not?
The exercises run on the server with a limit on steps and time, so an infinite loop cannot run forever. Excel has no such limit; there the macro runs until you interrupt it.
Is there an equivalent of Step?
No, with Do you decide how the variable changes. r = r + 2 visits every other row, r = r - 1 goes backwards.
Every loop compared, with a table of which one fits when: VBA loops overview.