VBA For Loop Syntax: Examples and Common Variations

VBA & macros · Updated November 18, 2026

In VBA, a For...Next loop repeats code for a counter that moves from a starting value to an ending value: write For counter = startValue To endValue, put the repeated statements below it, and close with Next counter. Add Step increment when the counter should move by a different amount or in reverse.

Basic For…Next syntax

The standard loop has four parts: the counter variable, its starting value, its ending value, and the statements to repeat. The Step clause is optional. If you leave it out, VBA increases the counter by 1 each time.

  • Counter: A numeric variable that changes as the loop runs. A Long is a practical choice for row numbers and other whole-number counts.
  • Start and end values: The first and last values in the intended sequence. VBA includes the end value if the sequence reaches it.
  • Loop body: The statements VBA executes once for each counter value.
  • Next: Marks the end of the loop body and advances the counter. Naming the counter after Next is optional, but it makes nested loops easier to read.

For example, a loop from 1 to 4 runs four times, with the counter taking the values 1, 2, 3, and 4. If the start is greater than the end while the step is the default positive 1, the loop body does not run. A loop whose counter is already at its end value runs once.

How the loop progresses

When VBA enters a For...Next loop, it sets the counter to the starting value, checks whether that value is within the limit, runs the body if it is, then applies the step and checks again. With the usual positive step, it continues while the counter has not passed the end value. With a negative step, it counts downward and continues while the counter has not gone below the end value.

The start, end, and step expressions are evaluated when the loop begins. Changing a variable used as the end value from inside the loop does not reset the loop’s original limit. If a loop should stop early based on a condition, use a deliberate condition and, where appropriate, Exit For rather than expecting an updated end variable to change the current loop.

Choose a counter type that can hold the values involved. Long is generally safer than the older 16-bit Integer for Excel row numbers: a worksheet can contain far more rows than an Integer can represent. Avoid a zero step because it does not move the counter and can leave the loop running indefinitely when its initial value is within the limits.

For loop example for worksheet rows

A numeric loop is useful when you need a row number, a fixed number of repetitions, or a predictable sequence. This macro writes 1 through 10 in cells A2:A11 on the first worksheet in the workbook containing the macro:

Sub WriteSequence()
    Dim i As Long
    Dim firstRow As Long
    Dim lastRow As Long

    ' Set the worksheet row limits for this example.
    firstRow = 2
    lastRow = 11

    ' Write a sequence into column A.
    For i = firstRow To lastRow
        ThisWorkbook.Worksheets(1).Cells(i, 1).Value = i - firstRow + 1
    Next i
End Sub

The worksheet row is the counter, while the value written is adjusted so the first cell receives 1 rather than 2. In Excel, Cells(row, column) uses numeric row and column indexes, so column 1 means column A. Using ThisWorkbook makes the target workbook explicit; unqualified references such as Cells(i, 1) can instead refer to whichever worksheet is active.

Before running a macro that changes workbook contents, save a copy of the workbook. VBA macro changes cannot be undone with Ctrl+Z, so a backup is the simplest way to recover from an unintended edit.

For Each versus For…Next

Use For...Next when the loop is driven by a count or index. Use For Each...Next when you want to visit each item in a collection, such as every cell in a range or every worksheet in a workbook. You do not have to calculate an item’s position or increment an index yourself.

This example visits cells A2:A20 on the first worksheet and converts non-error values to uppercase. It is intended for cells containing text; applying it to a mixed column can change how values are represented, so adjust the condition for your data.

Sub UppercaseTextCells()
    Dim ws As Worksheet
    Dim cell As Range

    ' Use the first worksheet in the workbook containing this macro.
    Set ws = ThisWorkbook.Worksheets(1)

    ' Visit each cell in the specified range.
    For Each cell In ws.Range(ws.Cells(2, 1), ws.Cells(20, 1))
        If Not IsError(cell.Value) Then
            If VarType(cell.Value) = vbString Then
                cell.Value = UCase$(cell.Value)
            End If
        End If
    Next cell
End Sub

The control variable in a range loop is declared as Range. In other collections, the variable must have a type suitable for the items being returned, or it can be declared as a Variant where appropriate. Changing a cell’s value while iterating a range is common; deleting or adding items to a collection during a For Each loop can make the iteration harder to reason about. For row deletion, a backwards numeric loop is often the clearer option.

Using Step to skip or reverse values

Step controls how much VBA adds to or subtracts from the counter after each pass. A step of 2 visits every other number; a negative step counts downward. Make sure the step direction matches the start and end values, or the body may not run at all.

Sub FillEveryOtherRow()
    Dim rowNum As Long

    ' Write values into rows 2, 4, 6, 8, and 10.
    For rowNum = 2 To 10 Step 2
        ThisWorkbook.Worksheets(1).Cells(rowNum, 1).Value = rowNum
    Next rowNum
End Sub

To count backward from 10 to 1, use For i = 10 To 1 Step -1 and close it with Next i. This direction is especially useful when deleting rows that meet a condition. Deleting a row shifts later rows upward; proceeding from the bottom reduces the risk of skipping a row that has moved into the position just processed.

Nested loops and early exits

A nested loop is a loop inside another loop. The inner loop completes all of its passes for each single pass of the outer loop. For example, the following macro fills a small rectangular range with a simple row-and-column label:

Sub FillSmallGrid()
    Dim rowNum As Long
    Dim colNum As Long

    ' Fill cells A1:C3 with labels based on their coordinates.
    For rowNum = 1 To 3
        For colNum = 1 To 3
            ThisWorkbook.Worksheets(1).Cells(rowNum, colNum).Value = _
                rowNum * 10 + colNum
        Next colNum
    Next rowNum
End Sub

Each For needs its own matching Next. Indenting the inner loop and naming both counters helps prevent mismatched loop endings. Avoid reusing the same counter for both levels because the inner loop would interfere with the outer loop’s progress.

Use Exit For to leave the nearest enclosing For or For Each loop early. It is useful when a search finds the item it needs, or when continuing would serve no purpose. In nested loops, an Exit For exits only the innermost loop, not every loop around it. A separate flag or additional logic may be needed to end multiple levels.

Common mistakes and safe habits

  • Wrong step direction: A positive step does not count down from a larger start to a smaller end. Use a negative step for a descending sequence.
  • Off-by-one limits: The end value is included when the sequence reaches it. Check whether a range should include its final row or stop just before it.
  • Using the wrong worksheet: Unqualified Cells and Range references may act on the active sheet. Qualify them with a worksheet variable or an explicit workbook reference.
  • Changing the collection being traversed: Deleting rows while moving top to bottom can skip records as rows shift. Loop backward when deletion is required.
  • Unbounded or non-advancing loops: A counter should change predictably and the end condition should be reachable. A zero step is a common cause of a loop that does not progress.
  • Assuming macros can be undone: Ctrl+Z does not reverse VBA changes. Save a backup before running code that edits data, formulas, or formatting.

For reliable worksheet automation, define variables, qualify worksheet references, and test on a copy with a small range first. If the loop processes data that may contain errors or blanks, include checks suited to those values rather than assuming every cell contains ordinary text or a number.

Where to enter and run VBA

In Excel for Microsoft 365 on Windows, open the Visual Basic Editor with Alt+F11, insert a standard module, and paste a procedure there. You can also open the editor from the Developer tab’s Visual Basic command. If the Developer tab is hidden, enable it in Excel’s ribbon customization settings. Run a procedure from the editor, or use the Developer tab’s Macros command to select and run a macro.

On a Mac, Excel also supports VBA, though some object-model features and keyboard shortcuts differ from Windows. The Visual Basic Editor is commonly opened with Option+F11; on some keyboards, you may need to hold Fn as well. Excel for the web does not run or edit VBA macros. A macro-enabled workbook should be saved in a format that supports macros, such as .xlsm, and macros should be enabled only when the workbook and its source are trusted.

Frequently Asked Questions

What is the basic syntax for a For loop in VBA?
Use For counter = startValue To endValue, place the repeated statements beneath it, and finish with Next counter. Add Step increment before the loop body if the counter should move by a value other than 1.

Does VBA include the end value in a For loop?
Yes, if the counter sequence reaches the end value, VBA runs the body for that value. For example, a loop from 1 to 3 with the default step runs for 1, 2, and 3.

How do I make a For loop count backward?
Give it a negative step, such as For i = 10 To 1 Step -1, and close the loop with Next i. The start must be above the end for this descending example.

What is the difference between For and For Each in VBA?
For...Next advances a counter through a sequence, which suits indexes and fixed counts. For Each...Next visits each item in a collection, such as each cell in a specified range.

Why does my VBA For loop run only once or not at all?
Check the start, end, and step values, including the direction of the step. A loop with a default positive step will not run when its start is already greater than its end, while matching start and end values normally produce one pass.

Related

Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.

More in VBA & macros

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.