Excel VBA For Each Loop: How to Use It
In this article
A For Each loop in Excel VBA is the cleanest way to run the same block of code on every item in a collection — every worksheet in a workbook, every cell in a range, every shape on a sheet, or every file in a folder. It works because VBA collections know how many items they contain, so you do not have to track an index or worry about the upper bound changing while the loop runs. The shortest working pattern is: declare an object variable, write For Each obj In collection, put your action inside the loop, and close with Next obj. Everything below explains how to set that up safely, where it goes wrong, and how to debug it.
What You'll Need
- Microsoft Excel on Windows or Mac (the VBA editor is included in all desktop editions; it is not available in Excel for the web).
- The Developer tab enabled, or you can press Alt+F11 (Windows) or Fn+Option+F11 (Mac) to open the editor directly.
- A workbook you can test on. Use a copy of any real file — loops that write to cells cannot be undone with Ctrl+Z once the macro finishes.
- Macros enabled for the file. If the workbook is saved as .xlsx, save it as .xlsm before adding code, otherwise the macro is lost on close.
Step-by-Step
- Open the VBA editor. Press Alt+F11 on Windows or Fn+Option+F11 on Mac. In the Project Explorer on the left, find your workbook and right-click it to choose Insert > Module. A blank code window appears. Menu labels can differ slightly between Excel versions, but Insert > Module has been stable for many releases.
- Start a Sub procedure. Type
Sub LoopExample()and press Enter. VBA adds the matchingEnd Subautomatically. All your code goes between those two lines. - Declare an object variable for the loop item. The variable must be an Object type — a Worksheet, Range, Shape, or Object. For example:
Dim ws As Worksheet. Using a specific type gives you IntelliSense and catches typos at compile time; using plainObjectworks but is harder to debug. - Write the For Each line. The syntax is
For Each ws In ThisWorkbook.Worksheets. The collection goes on the right ofIn. Common collections includeThisWorkbook.Worksheets,ActiveSheet.Range("A1:A10"),ActiveSheet.Shapes, andWorkbooks. - Add the action inside the loop. Indent one level and write what should happen to each item. For a worksheet loop, a safe first test is
Debug.Print ws.Name, which writes each sheet name to the Immediate Window (press Ctrl+G to view it). This proves the loop is visiting every item before you change anything. - Close the loop with Next. Type
Next ws. The variable name afterNextis optional but recommended — it makes nested loops readable and helps VBA flag mismatches. - Run the macro. Press F5 with the cursor inside the procedure, or use Run > Run Sub. Watch the Immediate Window to confirm each item was processed. If nothing appears, check that the Immediate Window is open.
- Adapt to cells. To loop every cell in a range:
Dim c As RangethenFor Each c In Range("A1:A20"). Inside the loop,c.Valuereads or writes the cell. Note that looping a multi-area selection or a range containing hidden rows still visits hidden cells — For Each does not skip them. - Adapt to shapes or files. For shapes:
Dim shp As ShapethenFor Each shp In ActiveSheet.Shapes. For files in a folder, use aFileSystemObjectcollection orDir— For Each works directly only with collections that expose an enumerator, and the folder'sFilescollection does. - Save as .xlsm and test on a copy. Close the editor, save the workbook in macro-enabled format, and run the macro once on duplicate data before using it on anything important.
Common Mistakes
- Declaring the loop variable as a value type.
Dim i As IntegerthenFor Each i In ...fails at compile time. The loop variable must be an Object. - Deleting items while looping. Removing a worksheet or shape inside a For Each loop can skip the next item or throw an error. Collect the items to delete in an array or use a reverse
For i = n To 1 Step -1loop instead. - Assuming For Each goes in a set order. Collection order is usually the order items were added, but do not rely on it for worksheets if the user can reorder tabs. If order matters, loop by index.
- Forgetting that hidden rows are still visited. A For Each over A1:A100 touches hidden cells. Filter or check
EntireRow.Hiddenif you need to skip them. - Modifying the collection inside the loop. Adding a worksheet while looping
Worksheetscan cause the loop to run longer than expected or hit the new sheet. - Leaving
On Error Resume Nexton. It hides the real error and makes a broken loop look like it ran fine.
Tips
- Use
Debug.Printinside the loop during development to see exactly which item is being processed and in what order. - Turn off
Application.ScreenUpdating = Falsebefore a long loop and set it back toTrueat the end — this makes loops over many cells or sheets noticeably faster. - Use
ThisWorkbookrather thanActiveWorkbookwhen looping worksheets, so the macro still works if the user switches windows mid-run. - For large ranges, read the range into a Variant array, process the array, then write it back in one go. A For Each over 100,000 cells is slow; an array loop is far faster.
- Name the loop variable after what it holds —
ws,c,shp— so nested loops stay readable.
Troubleshooting
If the macro does nothing, first check that the cursor is inside the correct procedure and that the Immediate Window is open. If you get a "Type mismatch" error on the For Each line, the loop variable is not an Object — change the declaration. If you get "Object required", the collection on the right of In is empty or misspelled; test it with a single Debug.Print before the loop. If the loop runs but skips items, you are probably deleting or adding items inside it — restructure as described above. If Excel freezes, press Ctrl+Break (Windows) or Cmd+Period (Mac) to interrupt, then add DoEvents inside long loops. If changes cannot be undone, that is normal for macros — restore from a saved copy rather than trying to reverse the loop.
Frequently Asked Questions
What is the difference between For Each and For Next?
For Each visits every item in a collection without you tracking a counter. For Next uses an index and is better when you need the position number, need to loop backwards, or need to delete items safely.
Can I use For Each on a range with multiple areas?
Yes, but For Each over a multi-area range visits each cell in each area, not each area as a block. Loop Range.Areas if you need area-by-area processing.
Does For Each work on arrays?
Yes, on a Variant array it visits each element. It does not work on a fixed-type array declared as a specific non-Variant type in every VBA version, so declare the array as Variant if in doubt.
Can I exit a For Each loop early?
Yes. Use Exit For inside the loop to stop immediately and continue after Next.
Why does my loop over worksheets fail after a sheet is deleted?
Deleting a sheet changes the collection while it is being enumerated. Collect the names first, then delete them in a separate loop.
Is For Each faster than For Next?
For small collections the difference is negligible. For very large ranges, neither is fast — reading into an array is the real speed-up.