Excel VBA Nested Loops: Step-by-Step Guide
In this article
A nested loop in Excel VBA is simply a loop placed inside another loop: the inner loop runs completely for each single pass of the outer loop. You write it by declaring two loop counters (for example i and j), opening an outer For...Next, opening an inner For...Next inside it, and closing both with separate Next statements. This is the standard way to walk a two-dimensional range, compare every row against every other row, or fill a grid of cells. Nothing needs to be installed beyond Excel itself and access to the Visual Basic Editor.
What You'll Need
- Excel for Windows or Mac with macros enabled (the Developer tab, or the ability to open the Visual Basic Editor with Alt+F11 on Windows, or the equivalent on Mac).
- A workbook saved as
.xlsm(macro-enabled) if you want to keep the code. - A blank sheet or a small table of sample data to test on. Work on a copy of any real workbook until the loop behaves correctly.
- Basic familiarity with variables,
For...Next, andCells(row, column).
Step-by-Step
- Open the editor. Press Alt+F11 (Windows) to open the Visual Basic Editor. On Mac, use the Developer tab or the Tools > Macro route in the Excel menu. Menu labels can differ slightly by version and platform.
- Insert a module. In the editor, choose Insert > Module. Code placed in a standard module can be run from anywhere in the workbook.
- Start the procedure. Type
Sub NestedLoopDemo()and press Enter. The editor addsEnd Subautomatically. - Declare your counters and a worksheet reference. Add lines such as
Dim i As Long, j As LongandDim ws As Worksheet, thenSet ws = ThisWorkbook.Worksheets("Sheet1"). UsingLongrather thanIntegeravoids overflow on large row counts. - Write the outer loop. For example
For i = 1 To 5. This controls the rows. - Write the inner loop inside it. Directly below, add
For j = 1 To 3. This controls the columns. Indent it so the nesting is visually obvious. - Put the work in the innermost block. A simple example:
ws.Cells(i, j).Value = i * j. This writes a small multiplication grid into A1:C5. - Close the inner loop first. Add
Next j, thenNext iafter it. Reversing the order, or using oneNextfor two loops, causes a compile error. - Add
End Subif it is not already there, then run the macro with F5. Step through with F8 to watch each cell fill in and confirm the inner loop really does complete before the outer counter advances. - Adapt to a dynamic range. Replace the fixed bounds with variables, for example
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Rowand useFor i = 2 To lastRowso the loop grows with your data. - Test on a copy, then save. Save as
.xlsmso the code persists. Keep a version of the workbook without macros as a backup.
Common Mistakes
- Reusing the same counter variable for both loops. The inner loop resets the outer counter and the code either loops forever or skips rows. Always use distinct names such as
iandj. - Closing the loops in the wrong order. The inner
Nextmust come before the outer one. - Forgetting to reset an accumulator. If you total values inside the inner loop, reset the total at the top of the outer loop, not once before everything.
- Writing to the sheet on every iteration. Cell writes are slow; a nested loop over thousands of rows can take minutes. Read into arrays and write back once.
- Off-by-one bounds.
For i = 1 To 10includes row 10. If row 1 is a header, start at 2. - No
ScreenUpdatingcontrol. Turning it off at the start and back on at the end (with error handling) makes long loops far less flickery.
Tips
- Use
Option Explicitat the top of the module so undeclared variables raise an error instead of silently defaulting. - Name counters meaningfully in complex code:
rowIdxandcolIdxread better thaniandj. - Add
Debug.Print i, jinside the inner loop to trace the order of execution in the Immediate Window. - Use
Exit Forto leave the inner loop early once a match is found, then decide whether the outer loop should also stop. - For pure grid work, a single loop over an array is often faster than a nested loop over cells.
Troubleshooting
If the macro does nothing, check that the code is in a standard module and that macros are enabled in the Trust Center. If you get a "Compile error: Next without For", count your For and Next lines; they must pair one-to-one and nest correctly. If the code runs forever, press Ctrl+Break (Esc may be needed on some Mac setups) to stop it, then check that the inner loop's counter is not being modified by the outer loop and that the bounds actually change. If cells fill in the wrong place, print i and j to the Immediate Window to see the real order. If you get a "Subscript out of range" error, the sheet name in Worksheets("Sheet1") does not match the tab name. If the workbook closes without saving changes, remember that macros do not run in .xlsx files and the code will be stripped on save.
Frequently Asked Questions
What is the difference between a nested loop and two separate loops?
Two separate loops run one after the other. A nested loop runs the inner loop fully for every single pass of the outer loop, which is what you need for two-dimensional work like rows and columns.
How many levels of nesting can VBA handle?
VBA allows several levels of nesting, but readability drops fast beyond two or three. If you need more, consider restructuring with arrays or helper procedures.
Why is my nested loop so slow?
Almost always because it reads or writes individual cells. Load the range into a variant array, loop over the array in memory, then write the array back to the sheet in one operation.
Can I use Do While inside a For loop?
Yes. Any loop type can be nested inside any other. Just make sure each loop type is closed with its matching statement (Next, Loop, or Wend).
How do I skip the header row?
Start the outer loop at 2 instead of 1, or check the cell value at the top of the loop and use If to skip it.
Does a nested loop work the same on Mac?
The loop syntax is identical. Only the editor shortcuts and some file-path behaviour differ between platforms.