VBA Double Loop: How Nested For Loops Work in Excel

VBA & macros · Updated November 18, 2026

A VBA double loop is a loop inside another loop: the outer loop runs once, and for each pass the inner loop completes all its iterations. In Excel, nested For...Next statements are a common way to process two dimensions, such as every row and column in a range.

What a VBA double loop does

“Double loop” is an informal name for a pair of nested loops; VBA does not have a special double-loop command. The first loop is the outer loop, and the loop placed inside it is the inner loop. You can nest For...Next loops, Do...Loop loops, or a mixture, though two For...Next loops are often easiest to follow when the number of repetitions is known.

Suppose a worksheet contains a rectangular table. An outer loop can select a row, while an inner loop visits each column in that row. After the inner loop reaches its final column, VBA moves to the next row and starts the inner loop again. This is why a nested loop is useful for tasks such as checking every cell, building a grid, comparing combinations, or calculating a total for each row.

The total number of inner-loop executions is the number of outer iterations multiplied by the number of inner iterations. A loop over 100 rows and 4 columns therefore visits 400 cell positions. That count matters when choosing a loop structure for large ranges.

How the loop order works

VBA follows the statements from top to bottom. When execution reaches an inner For statement, it runs that loop through its full range before returning to the outer loop. The outer counter changes only after the inner loop reaches its Next statement.

  1. The outer loop sets its counter to the starting value.
  2. The inner loop runs from its own starting value to its ending value.
  3. VBA returns to the outer loop, advances its counter, and repeats the inner loop.
  4. The procedure continues after the outer loop ends.

For a worksheet grid, the outer counter often represents a row number and the inner counter a column number. You can reverse that arrangement, but it changes the order of visits: row-first processing moves across each row, while column-first processing moves down each column. The result may be the same for independent calculations, but the order matters if each visit changes data used by a later visit.

A basic nested For loop example

This macro writes a small multiplication table into cells A1:E5 on the active worksheet. The row counter and column counter identify the destination cell, and their product supplies the value. It is deliberately small so that the loop order is visible.

Sub MakeSmallTable()
    Dim ws As Worksheet
    Dim rowNum As Long
    Dim colNum As Long

    Set ws = ActiveSheet

    ' Fill a five-row by five-column grid.
    For rowNum = 1 To 5
        For colNum = 1 To 5
            ws.Cells(rowNum, colNum).Value = rowNum * colNum
        Next colNum
    Next rowNum
End Sub

In the first pass, rowNum is 1. The inner loop writes 1 through 5 across the first row. The outer loop then advances to row 2, and the inner loop writes that row’s five values before moving on. Because the code writes to A1:E5, existing contents in those cells will be replaced; change the destination or use an empty area if you need to preserve them.

The counters are declared as Long, an integer type suitable for ordinary worksheet row and column indexes. Declaring variables makes their purpose clearer and helps avoid errors caused by misspelled or unexpectedly typed variables.

Summing several columns for each row

A more practical pattern is to run an inner loop over a set of columns, accumulate a value, and store one result for each outer-loop row. In the example below, the source data is assumed to be numeric and located in A2:D101. The macro writes each row’s total to column E on the same row.

Sub TotalEachRow()
    Dim ws As Worksheet
    Dim rowNum As Long
    Dim colNum As Long
    Dim rowTotal As Double

    Set ws = ActiveSheet

    ' Add columns A through D for each row.
    For rowNum = 2 To 101
        rowTotal = 0
        For colNum = 1 To 4
            rowTotal = rowTotal + CDbl(ws.Cells(rowNum, colNum).Value)
        Next colNum
        ws.Cells(rowNum, 5).Value = rowTotal
    Next rowNum
End Sub

The inner loop uses column numbers 1 through 4, which correspond to A through D. Once it has added those four cells, the macro writes the accumulated total to column 5, or E. Resetting rowTotal to zero at the start of each outer-loop pass is essential; without that reset, each row’s result would include values from earlier rows. Since CDbl converts a value to a number, this example expects numeric source cells. Validate or handle text and error values before using a similar conversion on mixed data.

Choosing loop bounds and direction

The loop bounds determine exactly which cells or items are processed. In the examples, the bounds are fixed, which is appropriate when the table size is known. For data that changes in length, you can calculate the last used row and use that value as the outer loop’s endpoint. The correct method depends on how the worksheet is structured: a column with occasional blanks, for example, may not have the same meaningful endpoint as a continuously filled column.

Use Step when a counter should advance by more than one or move backward. A loop such as For rowNum = 10 To 2 Step -1 processes rows in descending order. Working upward is useful when deleting rows, because removing a row does not shift unprocessed rows above it. By contrast, deleting while moving downward can cause the next row to shift into the position just processed and then be skipped.

VBA includes both endpoints in a standard For loop. Thus, For colNum = 1 To 4 runs four times, not three. Check whether your worksheet uses headers or starts data below row 1; a loop that begins at row 1 may accidentally include a heading.

Common problems and how to avoid them

  • Reusing one counter: Give the outer and inner loops separate variables. If a counter is changed unexpectedly inside a loop, the sequence can become difficult to reason about.
  • Putting Next statements in the wrong order: Close the inner loop first, then the outer loop. Indent the code so each For is visually paired with its matching Next.
  • Using the wrong row or column index: Cells(rowNum, colNum) expects the row number first and the column number second. Reversing them can write to a different part of the worksheet.
  • Forgetting to reset a running total: Initialize accumulators inside the outer loop when each row needs its own result.
  • Including a header or skipping the last record: Confirm the starting and ending values against the actual data range. Remember that both endpoints are included.
  • Assuming every cell has the expected type: Blank cells, text, and Excel error values may need explicit handling before a calculation or conversion.

When debugging, place the insertion point inside the procedure and use F8 in the Visual Basic Editor to execute one statement at a time on Windows. Watch the counter values and confirm the cell reference at each step. On a Mac, the keyboard shortcut can depend on the keyboard and system settings; use the editor’s Step Into command if the function key shortcut is intercepted.

Performance: when nested loops are slow

Nested loops are not automatically inefficient. A few hundred or a few thousand cell visits are often reasonable, but accessing worksheet cells one by one can become slow when a macro processes a very large range or repeats expensive operations such as formatting or recalculation. A loop with 20,000 visits performs 20,000 inner operations; adding another nested pass can multiply that work again.

For larger datasets, a common improvement is to read a range into a VBA array, process the array in memory, and write the results back to the sheet in a block. This reduces repeated communication between VBA and the worksheet. It requires more setup and careful mapping between array positions and worksheet rows, so a simple cell loop may be clearer for small ranges. Also avoid selecting or activating each cell inside a loop unless the task genuinely requires interaction with the selection; direct references such as ws.Cells(rowNum, colNum) are generally simpler.

Do not optimize solely because a loop is nested. First check how many times it runs and what each pass does. If a macro is slow, the bottleneck may be repeated formatting, formulas recalculating, or a large amount of worksheet access rather than the nesting itself.

Alternatives and when to use them

A double loop is a good fit when the task must inspect or change individual positions in a two-dimensional grid. If the goal is just to total four columns, an Excel formula or a worksheet function may be shorter than a macro. If a macro must process every row but only a single column, one loop is enough. If the data is a structured Excel table, a loop over its data rows can make the code adapt more naturally than fixed row numbers, though the table and column references must be set correctly.

Excel’s built-in tools can also avoid VBA for common jobs. Sort, Filter, conditional formatting, and worksheet formulas are often easier to maintain when other users need to inspect or update the workbook. VBA is more useful for repeatable multi-step actions, custom processing, or tasks that are awkward to perform manually. The right choice depends on whether automation, transparency, flexibility, or ease of maintenance matters most.

Running VBA safely in Excel

In Excel for Microsoft 365 on Windows, open the Visual Basic Editor with Alt+F11, then choose Insert > Module and paste the procedure into the module. You can also open the editor from Developer > Visual Basic. If the Developer tab is hidden, turn it on through File > Options > Customize Ribbon. On Mac, use Developer > Visual Basic when available; Option+F11 may open the editor, though some keyboards require the Fn key as well.

Save a copy of the workbook before running a macro. VBA changes cannot be undone with Ctrl+Z, and the sample macros write directly to worksheet cells. Save a workbook containing VBA as an Excel Macro-Enabled Workbook (.xlsm) if you need to keep the code. Only enable macros from sources you trust, and note that some Windows-specific VBA features, such as certain ActiveX controls or Windows API calls, may not work on Mac.

Frequently Asked Questions

What is a double loop in VBA?
A double loop is one loop placed inside another. The inner loop completes its full sequence for every pass of the outer loop, making the pattern useful for processing rows and columns.

How many times does a nested loop run?
Multiply the number of outer-loop iterations by the number of inner-loop iterations, assuming the inner bounds are the same each time. For 10 outer passes and 4 inner passes, the inner statements run 40 times.

Can VBA have more than two nested loops?
Yes. You can nest additional loops, but each one increases the work and can make the code harder to understand. Use clear counter names and indentation, and consider whether the same task can be expressed more simply.

Does Exit For stop both loops?
No. Exit For exits only the nearest enclosing For loop. To leave both nested loops, use a flag checked by the outer loop, or structure the procedure so that another exit method is clear and maintainable.

Why is my VBA double loop skipping cells?
Check the start and end values, the order of row and column arguments in Cells(row, column), and whether the counter is changed elsewhere. When deleting rows, process from bottom to top to avoid shifting unprocessed rows into positions the loop has already passed.

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.