VBA Excel: Loop For Each Row in a Range
In this article
The fastest way to loop over every row of a range in VBA is a For Each loop over Range.Rows, or a numeric For loop from the range's first row to its last row. Use For Each … In rng.Rows when you just need to read or test each row, and use a numbered For loop when you need the row index for lookups, offset writes, or deletion. Both work in any Excel version on Windows or Mac; only the keyboard shortcuts that open the VBA editor differ slightly by platform and version.
What You'll Need
- Excel on Windows or Mac with a workbook you can save as
.xlsm(macro-enabled). If the workbook is saved as.xlsx, macros are stripped when you close it. - The Developer tab visible: File > Options > Customize Ribbon > tick Developer in the main list (Windows), or Excel > Preferences > Ribbon & Toolbar > enable Developer (Mac). Menu names vary a little by version, so look for the closest match.
- A sheet of data with a clear first and last row, ideally with headers in row 1 that you exclude from the loop.
- Macro security left at its default setting. Don't lower it to make code run; save in a trusted location instead.
Step-by-Step
Open the VBA editor. Press
Alt+F11on Windows; on Mac useOption+F11. Menus and shortcuts can differ by version, so if nothing happens check the Developer tab and click Visual Basic.Insert a module. In the editor choose Insert > Module. Code in a standard module can be run with
Alt+F8(Windows); code placed in a sheet module runs on that sheet's events instead. A visible, runnable macro goes in a module.Start the routine and declare variables. Use explicit types so mistakes surface early:
Sub LoopRows() Dim ws As Worksheet Dim rng As Range Dim rowRange As Range Set ws = ThisWorkbook.Worksheets("Sheet1")Point at the range you want to loop. Prefer a range that ends at the last used row rather than a fixed block, so the macro keeps working as data grows:
Set rng = ws.Range("A2:A" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row)This covers A2 down to the last filled cell in column A. Include more columns if the loop needs them, for example
"A2:D" & ….Write the
For Eachloop over rows.rng.Rowsgives you each row of that range as its own Range object:For Each rowRange In rng.Rows Debug.Print rowRange.Row, rowRange.Cells(1, 1).Value Next rowRange End SubrowRange.Rowis the worksheet row number;rowRange.Cells(1, 1)is the first cell in that row of the range. PressF5to run and check the Immediate window (Ctrl+G) for output.Do your work inside the loop. Test a condition before acting, so blank or header rows don't get processed:
If Trim(rowRange.Cells(1, 1).Value) <> "" Then rowRange.Cells(1, 2).Value = UCase(rowRange.Cells(1, 1).Value) End IfHere the loop copies column A into column B in upper case, row by row.
Use a numbered loop instead when you need the index. A
For r = firstRow To lastRowloop is often clearer and lets you address whole rows withws.Cells(r, "B")orws.Range("A" & r):Dim r As Long, lastRow As Long lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row For r = 2 To lastRow If ws.Cells(r, "A").Value <> "" Then ws.Cells(r, "B").Value = ws.Cells(r, "A").Value * 2 End If Next rSpeed it up on large data. Wrap the loop with
Application.ScreenUpdating = FalseandApplication.Calculation = xlCalculationManualbefore it, then restore both toTrueandxlCalculationAutomaticafter. Restore them even if the loop errors, using an error handler or by setting them immediately afterNext.Save and run. Save the workbook as
.xlsm, then run the macro from the editor withF5or from the sheet with Developer > Macros (Alt+F8on Windows). Test on a copy of the data first.
Common Mistakes
- Looping over a whole column.
Range("A:A")has over a million rows; always bound the range withEnd(xlUp).Rowor a fixed last row. - Including the header row. Starting at row 1 often overwrites titles with converted values. Start at row 2 when row 1 is a header.
- Deleting rows inside a forward loop. Deleting shifts rows up, so the next row is skipped. Loop backwards (
For r = lastRow To 2 Step -1) when deleting. - Using
Cells(1, 1)on the worksheet instead of on the row range.rowRange.Cells(1, 1)is relative to the range;ws.Cells(1, 1)is always A1. - Forgetting
Setfor object variables.rng = Range("A2:A10")fails; it must beSet rng = …. - Assuming
Valueis text. Numbers stored as text, dates, and error values such as#N/Abreak comparisons. UseTrim,IsNumeric, orIsErrorchecks. - Relative column references drifting.
rowRange.Cells(1, 2)means column B only because the range starts at column A; if the range starts at C, it means D.
Tips
- Work with values in memory and write results back, or read the used range into a variant array for very large datasets; cell-by-cell writing is slow.
- Use
Longrather thanIntegerfor row counters: worksheets have far more rows thanIntegercan hold. - Name your loop variable meaningfully (
rowRange,dataRow) so nested loops stay readable. - Add
Option Explicitat the top of the module to catch undeclared variables. - Address columns by their letter or a constant so a later inserted column doesn't silently change what the loop reads.
- Keep a copy of the original data; macros that write in place are unforgiving of a wrong column index.
Troubleshooting
- "Compile error: Expected: =" or "Object required": you assigned a range without
Set, or used a misspelled variable name. - "Subscript out of range": the worksheet name in
Worksheets("Sheet1")doesn't match a real tab. Check for trailing spaces and exact spelling. - Runtime error 91, object variable not set: the range was never assigned, usually because
End(xlUp).Rowreturned 1 and the range became invalid, or the sheet is empty. Add a guard that exits the sub whenlastRow < 2. - Loop runs far too long or stops at the wrong row: the last-row calculation picked up a stray value far down the column, or blank cells inside the data ended the range early. Check with
Ctrl+Endwhat Excel thinks the last cell is. - Nothing happens: the code is in the wrong module, there's no
Sub … End Sub, or the Immediate window is hidden. PressCtrl+Gto show it. - Results look one row off: the loop starts at 1 instead of 2, or the relative column index in
rowRange.Cellsis wrong. PrintrowRange.Rowto confirm which row you're on. - The macro vanished after reopening: the file was saved as
.xlsx. Save as.xlsm; the original macro code cannot be recovered from that file. - Excel is slow or frozen: screen updating and calculation may still be off from a crashed run. Reset both to
Trueand automatic in the Immediate window, and close and reopen the workbook if it stays unresponsive.
Frequently Asked Questions
What's the difference between For Each and For loops over rows?
For Each walks each row object without you tracking a number; a numeric For loop gives you the row index, which you need for offsets, deletion, or cross-referencing another range. Both are equally valid; pick by whether the index matters.
How do I loop only the rows that have data?
Bound the range to the last used row with Cells(Rows.Count, col).End(xlUp).Row, then skip blanks inside the loop with a check on the key cell.
Why does my loop skip rows after I delete some?
Deleting shifts the rows below upward while the counter moves down, so some rows are never examined. Loop backwards with Step -1 when deleting.
Can I loop a range on a sheet other than the active one?
Yes. Fully qualify every reference with a worksheet object, as in ws.Range(...) and ws.Cells(...). Unqualified references default to the active sheet and can produce wrong results or errors.
How do I stop the loop when a row is blank?
Use Exit For inside the loop once your blank test is true. That ends the loop immediately and continues with the code after Next.
Does a row loop work the same on Excel for Mac?
The VBA language and range objects behave the same; only editor shortcuts and some menu paths differ. If a shortcut doesn't respond, use the Developer tab buttons instead.