Coding

VBA For Loop: For...Next Syntax and Examples

A VBA for loop repeats a block of code a set number of times, written as For i = 1 To 10 ... Next i. The counter goes up by 1 each pass unless you add Step, and Exit For leaves the loop early.

VBA For...Next syntax

This is the form from Microsoft's reference for the statement:

For counter = start To end [Step step]
    [statements]
    [Exit For]
    [statements]
Next [counter]

The parts work like this:

  • counter is a numeric variable. According to the documentation it cannot be a Boolean or an array element.
  • start is the value of the counter on the first pass.
  • end is the final value of the counter.
  • step is optional. It is the amount added to the counter after every pass, and it defaults to 1.

The simplest loop prints the numbers 1 to 5 to the Immediate window (open it with Ctrl+G in the VBA editor):

Sub CountToFive()
    Dim i As Long
    For i = 1 To 5
        Debug.Print i
    Next i
End Sub

Example output: 1, 2, 3, 4, 5, one per line. Declaring the counter as Long is a habit worth keeping: spreadsheet row numbers can exceed the range of Integer (32,767), and Long avoids an overflow error in loops that walk down a sheet.

How the loop decides whether to run

Microsoft's page gives the exact rule. After the statements in the body run, step is added to the counter, and the same test is applied again. The test depends on the sign of the step:

Step valueLoop runs while
Positive or 0counter <= end
Negativecounter >= end

Two practical consequences follow from the table. First, if the start value is already past the end value for the direction you chose, the body never runs. For i = 10 To 1 with the default step of 1 does nothing, because 10 is not less than or equal to 1. To count down you must say so with Step -1. Second, the table lists "positive or 0" together, which means a step of 0 passes the test for as long as the counter is at or below the end value. Because the counter never changes, you would get a loop that never ends unless something inside it calls Exit For. Avoid a zero step.

Step: counting by twos, tens or backwards

Add Step to change the increment. This loop visits only odd numbers:

Dim i As Long
For i = 1 To 9 Step 2
    Debug.Print i
Next i

Example output: 1, 3, 5, 7, 9. The next value after 9 would be 11, which is greater than 9, so the loop stops. A negative step counts down:

For i = 10 To 1 Step -1
    Debug.Print i
Next i

Example output: 10, 9, 8 and so on down to 1. Counting down is also the safe direction when you delete rows from a worksheet inside a loop. If you walk down and delete row 5, the old row 6 moves up into row 5 and your counter skips it. Walking from the bottom up avoids that, because deleting a row only shifts rows you have already visited.

Sub DeleteBlankRowsInColumnA()
    Dim rowIndex As Long
    For rowIndex = 20 To 1 Step -1
        If Cells(rowIndex, 1).Value = "" Then
            Rows(rowIndex).Delete
        End If
    Next rowIndex
End Sub

This runs against the active sheet and really deletes rows, so try it on a copy of your workbook first. The fixed bound of 20 keeps the example short; in real code you would compute the last used row instead.

Looping over cells with a counter

A for loop with Cells(row, column) is the standard way to process a column one row at a time. This one writes the square of each row number into column B, for rows 1 to 10:

Sub FillSquares()
    Dim rowIndex As Long
    For rowIndex = 1 To 10
        Cells(rowIndex, 2).Value = rowIndex * rowIndex
    Next rowIndex
End Sub

Here the loop counter doubles as the row number, which is why the counter is named rowIndex and not i. A descriptive name makes the loop easier to read when it contains several nested references.

Exit For

Any number of Exit For statements may appear in the loop body. Microsoft notes that it is often used after testing a condition with If...Then, and that it transfers control to the statement immediately after Next. This loop stops at the first cell in A1:A10 that contains the text "stop":

Sub FindStop()
    Dim rowIndex As Long
    For rowIndex = 1 To 10
        If Cells(rowIndex, 1).Value = "stop" Then
            Debug.Print "Found in row " & rowIndex
            Exit For
        End If
    Next rowIndex
End Sub

In nested loops, Exit For exits only the loop it sits in. Per the Exit statement page, control passes to the loop one nesting level above. If you need to leave both loops, set a flag variable and check it in the outer loop, or move the loops into a Function and use Exit Function.

Nested for loops

You can place one For...Next inside another. The documentation's rule is to give each loop a unique variable as its counter. Here a nested pair fills a 5 by 5 multiplication table, starting at cell A1:

Sub MultiplicationTable()
    Dim rowIndex As Long
    Dim columnIndex As Long
    For rowIndex = 1 To 5
        For columnIndex = 1 To 5
            Cells(rowIndex, columnIndex).Value = rowIndex * columnIndex
        Next columnIndex
    Next rowIndex
End Sub

The inner loop runs completely for every pass of the outer loop, so the body executes 5 x 5 = 25 times. Each Next closes the nearest open For. Writing the counter name after Next is optional: Microsoft says that if you leave it out, execution continues as if it were included. Including it is still worth doing, because in a deeply nested block it shows which loop each line closes. If a Next appears before its matching For, VBA raises an error.

Changing the counter inside the loop

VBA allows you to assign to the counter inside the body, but the documentation carries a tip against it: changing the counter can make code harder to read and debug. If you want to skip values, use Step. If you want to stop, use Exit For.

For Each...Next: loop over items, not numbers

When you want every item in a collection or array, For Each removes the counter altogether:

For Each element In group
    [statements]
    [Exit For]
Next [element]

The loop body runs once for each element, and only if the group has at least one element. For collections, the element can be a Variant, a generic object variable or a specific object variable. For arrays, it can only be a Variant. You cannot use it on an array of user-defined types, because a Variant cannot hold one. A common use is going through the cells of a range:

Sub HighlightNegatives()
    Dim cell As Range
    For Each cell In Range("A1:A10")
        If cell.Value < 0 Then
            cell.Interior.Color = vbRed
        End If
    Next cell
End Sub

And here is the array version, with the Variant element the documentation requires:

Sub ListFruit()
    Dim fruit As Variant
    For Each fruit In Array("apple", "pear", "plum")
        Debug.Print fruit
    Next fruit
End Sub

Example output: apple, pear, plum. Exit For works in a For Each loop in the same way as in For...Next, and nested For Each loops need a unique element variable each.

Which loop should you use?

  • Use For...Next when you know the number of passes, need the index (for a row number, say), need to step by more than 1, or must count backwards.
  • Use For Each...Next when you just want every item in a range, collection or array and do not care about its position.
  • If the number of passes depends on a condition rather than a count, VBA has a separate Do...Loop, which the Exit statement page covers alongside For (Exit Do).

If you also write scripts outside Office, the same ideas appear in other languages with different syntax; for instance, see PowerShell for loop and foreach examples.

Common mistakes

  • Forgetting Step -1 when counting down. The loop body is skipped entirely, with no error.
  • Deleting rows while counting up. Rows shift under the counter and some are missed. Loop from the bottom instead.
  • Reusing a counter in nested loops. Each loop needs its own variable.
  • Using a Boolean or an array element as the counter. The documentation says neither is allowed. Use a plain numeric variable and read the array with it, for example values(i).

Frequently asked questions

What is the syntax of a for loop in VBA?
For counter = start To end [Step step], then the statements to repeat, then Next [counter]. The counter must be a numeric variable. If you leave out Step, the counter goes up by one each pass.
How do I count backwards in a VBA for loop?
Use a negative Step, with a start value that is larger than the end value. For i = 10 To 1 Step -1 runs ten times, from 10 down to 1. With a negative step the loop runs while the counter is greater than or equal to the end value.
How do I exit a for loop early in VBA?
Use Exit For, usually inside an If statement. It jumps to the statement after the matching Next. In nested loops it leaves only the loop it is written in, and control goes to the loop one level above.
Does VBA have a continue statement for loops?
Microsoft's documentation for the For...Next and Exit statements lists no Continue statement. A common workaround is to wrap the body in an If block so that the rest of the pass is skipped when the condition is not met.
What is the difference between For...Next and For Each...Next?
For...Next repeats a block while a numeric counter runs from a start to an end value. For Each...Next visits every element of an array or collection, so you do not manage a counter or know the item count. The element variable for an array must be a Variant.

Sources