VBA For Next Loop: Syntax, Examples, and Common Errors

VBA & macros · Updated November 18, 2026

A VBA For...Next loop repeats a block of code for a counter that moves through a specified range. In Excel, it is useful for predictable tasks such as checking rows, filling cells, or repeating an action a set number of times; the basic pattern is For counter = start To finish, followed by the code to repeat and Next counter.

How a For Next loop works

A For...Next loop has a counter, a starting value, an ending value, and an optional increment called Step. VBA assigns the starting value to the counter, runs the statements in the loop, and then advances the counter by the step amount. It repeats until the counter passes the ending value in the direction of travel.

For example, a loop from 1 to 4 with no Step specified uses an increment of 1. The loop body runs with counter values 1, 2, 3, and 4. The ending value is included when the counter reaches it. If the starting value is already beyond the ending value for the chosen direction, the loop body does not run.

The counter is a variable, usually declared as Long for row numbers or other whole-number counts. Declaring it makes the code easier to understand and helps catch spelling mistakes when the module uses Option Explicit. A counter should not be changed inside the loop body: doing so can make the sequence hard to follow or cause unexpected results.

Basic syntax and the Step option

The general form is For counter = start To end [Step increment], then one or more statements, then Next counter. The square brackets in that description mean the Step part is optional; do not type the brackets into VBA. When omitted, the increment is 1. A positive step counts upward, while a negative step counts downward.

This example prints the even numbers from 2 through 10 in the Immediate window:

Sub PrintEvenNumbers()
    Dim number As Long

    ' Advance by two on each pass.
    For number = 2 To 10 Step 2
        Debug.Print number
    Next number
End Sub

The output is 2, 4, 6, 8, and 10, each on its own line. A descending loop can use a negative step, as in For number = 5 To 1 Step -1. It visits 5, 4, 3, 2, and 1. The step must move toward the ending value; for instance, starting at 1 and counting toward 5 with Step -1 does not make progress toward the end and can fail to terminate as intended. Avoid a zero step because it does not advance the counter.

Loop through Excel worksheet rows

A common Excel use is to inspect a range one row at a time. The following macro checks values in column B on a worksheet named Data and writes Review in column C when a numeric value is at least 100. It determines the last used row in column A, then processes rows 2 through that row, treating row 1 as a header.

Sub MarkLargeValues()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim rowNum As Long

    ' Use the Data sheet in the workbook containing this code.
    Set ws = ThisWorkbook.Worksheets("Data")
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    ' Check each data row, leaving the header row untouched.
    For rowNum = 2 To lastRow
        If IsNumeric(ws.Cells(rowNum, "B").Value) Then
            If ws.Cells(rowNum, "B").Value >= 100 Then
                ws.Cells(rowNum, "C").Value = "Review"
            End If
        End If
    Next rowNum
End Sub

Here, rowNum is the loop counter and is used in the cell references. The Long type is suitable for Excel row numbers, which can exceed the range of the older Integer type. The macro writes to cells, so save a copy of the workbook before running it: VBA macros cannot be undone with Ctrl+Z. The code assumes the sheet exists and that column A reliably indicates which rows contain records.

Nested loops and looping across columns

You can put one For...Next loop inside another to work with a two-dimensional range. The inner loop completes all of its passes for each pass of the outer loop. Use a different counter for each loop so that the inner loop does not overwrite the outer loop’s position.

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

    ' Visit each cell in the specified 3-by-3 range.
    For rowNum = 2 To 4
        For colNum = 1 To 3
            If Cells(rowNum, colNum).Value < 0 Then
                Cells(rowNum, colNum).ClearContents
            End If
        Next colNum
    Next rowNum
End Sub

This example uses unqualified Cells, which refers to the active sheet. For more dependable workbook code, qualify those references with a worksheet variable, such as ws.Cells(rowNum, colNum), and set ws to the intended sheet. Nested loops can be useful for small grids, but looping through every cell in a large range can be slow; when practical, reading a range into an array and processing the array can reduce worksheet interaction.

Changing direction, stopping early, and deleting rows

Use a negative Step when the task needs to move backward. One important Excel example is deleting rows that match a condition. If rows are deleted while counting upward, the next row shifts into the deleted row’s position and may be skipped. Counting from the bottom toward the top avoids that particular problem.

Sub DeleteBlankIDs()
    Dim ws As Worksheet
    Dim rowNum As Long
    Dim lastRow As Long

    ' Save a copy before running because deleted rows cannot be restored with Ctrl+Z.
    Set ws = ThisWorkbook.Worksheets("Data")
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    ' Work upward so deleting a row does not shift unchecked rows past the counter.
    For rowNum = lastRow To 2 Step -1
        If Len(ws.Cells(rowNum, "A").Value) = 0 Then
            ws.Rows(rowNum).Delete
        End If
    Next rowNum
End Sub

Exit For offers another kind of control: it leaves the innermost active For loop immediately and continues with the statement after its matching Next. It is useful when a search has found what it needs, such as the first matching record. In nested loops, exiting the inner loop does not automatically exit the outer loop; add a flag or another control structure if the whole search must stop.

Common errors and debugging tips

A loop that runs too many times, not at all, or never finishes often has a mismatch between its starting value, ending value, and direction. Check that the step moves toward the end, that the intended end is inclusive, and that the range bounds are correct. If a loop processes rows, verify whether row 1 is a header and whether the selected column is the right one for finding the last row.

  • Missing or mismatched Next: Each For needs a corresponding Next. In nested loops, close the inner loop before the outer loop.
  • Wrong counter type: Use Long for Excel row counters rather than Integer, which has a much smaller maximum value.
  • Unqualified worksheet references: Cells, Rows, and Range can refer to the active sheet if not qualified. A user changing sheets can therefore affect where code operates.
  • Changing data while moving forward: Deleting rows or inserting rows can shift later positions. Consider iterating backward or collecting the target rows before changing the sheet.
  • Unexpected worksheet values: Blank cells, text, and Excel error values may need explicit handling before a numeric comparison or calculation.

To inspect a macro, place the cursor in it in the Visual Basic Editor and press F5 to run, or use the editor’s debugging controls to step through statements. In Excel for Windows, Alt+F11 opens the Visual Basic Editor; on a Mac, Option+F11 is commonly used, sometimes with Fn depending on the keyboard. You can also run a macro from Excel through Developer > Macros > Run. Test on a copy and use a small sample first, particularly when the code deletes or overwrites cells.

When to use For Next instead of another loop

Choose For...Next when the number of repetitions or the counter range is known or can be calculated before the loop starts. A row range from 2 to a known last row is a natural fit. So is repeating an operation a fixed number of times or stepping through a numeric sequence.

A Do...Loop is often clearer when repetition should continue until a condition changes and the number of passes is not known in advance. For example, a process might continue until a user enters a valid value. A For Each...Next loop is often preferable when visiting every item in a collection, such as each worksheet in a workbook, because it avoids managing a numeric index. These loop forms are not interchangeable in every situation, but choosing the one that expresses the stopping rule clearly makes code easier to maintain.

Running VBA in Excel safely

VBA runs in desktop Excel, including Microsoft 365 for Windows and Mac, though some object-model features and platform interactions can differ. Excel for the web does not run VBA macros; a workbook containing macros can be opened there, but use desktop Excel to execute VBA. Macros may also be blocked by security settings, and the exact prompt depends on how the workbook was obtained and the organization’s policies.

Only enable macros in files from a source you trust. A macro can edit or delete workbook content and may perform other actions permitted by its code. Save a separate copy before running code that changes data, and review the target worksheet and range in the code rather than assuming the active sheet is correct. Ctrl+Z cannot reverse actions performed by a macro; on Mac, Command+Z likewise does not provide a reliable undo for VBA changes.

Frequently Asked Questions

What does Next do in VBA?
Next marks the end of a For loop. VBA advances the loop counter by the step amount and checks whether another pass should run. Writing the counter after Next, as in Next rowNum, can make nested code easier to read.

Is the ending number included in a VBA For loop?
Yes. The loop body runs when the counter equals the ending value, provided the counter reaches it by the chosen step. A step that skips over the ending number may mean the counter never equals it, although the loop still stops once it passes the limit.

How do I count backward in VBA?
Set the start to a larger value than the end and use a negative step, for example For i = 10 To 1 Step -1. The counter visits 10 down to 1. This pattern is useful when deleting rows from a worksheet.

Can I exit a For Next loop early?
Yes. Use Exit For when a condition means the loop no longer needs to continue. It exits only the nearest enclosing For loop, so nested loops may need additional logic if the outer loop should stop too.

Why does my VBA loop skip rows after deleting one?
Deleting a row shifts the rows below it upward. If the counter then advances, the row that moved into the deleted position may be skipped. Loop from the last relevant row upward with Step -1, or identify rows first and delete them in a separate pass.

Can VBA loops run in Excel for the web?
No. Excel for the web does not execute VBA macros. Open the workbook in the desktop Excel application to run its VBA code; Microsoft 365 desktop Excel supports VBA on Windows and Mac, with some platform-specific differences.

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.