VBA loops: which loop to use when

Almost every useful macro works through a list, row by row or cell by cell. VBA has several loops for that. This page compares all of them with a short example each and points you to the lesson with exercises.

In short: if you know how many times it should run, use For … Next. If you go through every cell of a range or every sheet, use For Each. If a condition you do not know in advance decides when to stop, use Do While or Do Until.

Try it right now

Seven items, and column D is missing the line total. One loop with a single calculation line fills every row.

Task Write a macro LineTotals that fills column D with quantity times unit price for rows 2 to 8. Use a For Next loop with the counter i. Check also tests it with other quantities.

ABCD
1ItemQtyUnit priceTotal
2Copy paper A4104.95
3Lever arch file252.49
4Ballpoint pens, blue500.89
5Sticky notes121.79
6Black toner264.90
7Clear pockets53.20
8Staples81.15

Which loop to use when

LoopFits when …Lesson
For i = 2 To lastRow … Next iyou know the first and last row (often down to the last row)For Next
For i = lastRow To 2 Step -1you need to count backwards, for example when deleting rowsDelete rows
For Each cell In range … Nextyou want to handle every cell of a range, every sheet or every item of a collectionFor Each
Do While condition … Loopit should run as long as something is true, for example while column A is not emptyDo While and Do Until
Do Until condition … Loopit should run until something happens, for example until a target is reachedDo While and Do Until
Do … Loop While conditionthe body has to run at least once before the checkDo While and Do Until

For Next: counting

The counter runs from the start value to the end value. Step sets the increment; with a negative value the loop counts down.

Dim i As Long, s As String
For i = 10 To 1 Step -3
    s = s & i & " "
Next i
Debug.Print s   ' 10 7 4 1

You mostly need to count down when deleting: if the loop deletes row 5, row 6 moves up. Counting forwards, the loop would skip that row.

For Each: every item

For Each needs no counter. The variable stands for each cell of the range in turn, each sheet of the workbook or each item of a collection.

Dim cell As Range
For Each cell In Range("A1:A3")
    cell.Value = cell.Row * 10
Next cell   ' A1 = 10, A2 = 20, A3 = 30

The variable has to match what you loop over: As Range for cells, As Worksheet for sheets. A variable declared As Long does not work here.

Do While and Do Until: with a condition

Do loops check a condition instead of counting. While keeps going as long as the condition is true; Until keeps going until it becomes true. Put the condition after Loop and the body runs at least once.

Dim r As Long
r = 2
Do While Cells(r, 1).Value <> ""
    Cells(r, 3).Value = Cells(r, 2).Value * 2
    r = r + 1
Loop

The line r = r + 1 matters. Without it the loop checks the same row over and over and never stops.

The older While … Wend also works, but you cannot leave it early. Prefer Do While … Loop.

Leaving a loop early

Exit For leaves a For or For Each loop, Exit Do leaves a Do loop. That is handy when you search and want to stop at the first match.

For i = 2 To lastRow
    If Cells(i, 1).Value = "Boston" Then
        MsgBox "Found in row " & i
        Exit For
    End If
Next i

Endless loop: what now?

If the condition of a Do loop never changes, the macro runs forever. In real Excel you interrupt it with Ctrl+Break or Esc, then end it or step through it. In the exercises here the server stops such a macro after a short time and reports the endless loop.

Making loops faster

With long lists the slow part is not the loop but touching every single cell. Two things help: turn off screen updating while the macro runs (With and faster macros) and read the data into an array once, work there and write it back at the end (Arrays).

FAQ

Which loop is best?

There is no best one, only the right one. For Next for a known count, For Each for every item of a range or collection, Do While or Do Until when a condition decides when to stop.

How do I loop down to the last row?

Find the last row with Cells(Rows.Count, 1).End(xlUp).Row and use it as the end value of the For loop. Find the last row shows how it works.

Can I nest loops?

Yes, for example a loop over rows with a loop over columns inside. Give each loop its own counter and write the name after Next, so you can see which Next belongs to which For.

Is there an Exit While?

No. You cannot leave While … Wend early. Use Do While … Loop with Exit Do instead.

Start with your first loop

The For Next lesson shows step by step how a macro works through a whole list, with three exercises in your browser.

Go to the For Next lesson

Write to us

Choose language

Select your preferred language