The For Each...Next loop in VBA is the fastest way to repeat a block of code for every item in a collection, such as all cells in a range, all worksheets in a workbook, or all open workbooks. Instead of counting items and using an index, you let VBA handle the iteration: For Each element In group … Next element.
What Is a Collection in VBA?
In VBA, a collection is an object that holds a set of related items. The most common ones you’ll loop through are:
- Range – a group of cells (e.g.,
Range("A1:A10")) - Worksheets – all sheets in a workbook
- Workbooks – all open workbooks
- Shapes – all shapes on a worksheet
- Charts – all charts in a workbook
- Controls – all form controls on a UserForm
Every collection has a Count property and an Item method, but For Each lets you skip both. The loop automatically moves to the next item after each pass, and it stops when there are no more items.
Basic Syntax and a Simple Example
The syntax is straightforward:
For Each element In group
' statements to execute for each element
Next element
Here’s a real example that bolds every cell in column A that contains the word “urgent”:
Sub BoldUrgentCells()
Dim cell As Range
For Each cell In Range("A1:A100")
If InStr(1, cell.Value, "urgent", vbTextCompare) > 0 Then
cell.Font.Bold = True
End If
Next cell
End Sub
Notice that cell is declared as Range. For a collection of worksheets, you’d declare it as Worksheet, and for workbooks, Workbook. The loop variable must match the type of the items in the collection.
Looping Through Worksheets and Workbooks
One of the most common uses is to perform the same action on every worksheet:
Sub ListSheetNames()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
Debug.Print ws.Name
Next ws
End Sub
To loop through all open workbooks:
Sub CloseAllButActive()
Dim wb As Workbook
For Each wb In Workbooks
If wb.Name <> ThisWorkbook.Name Then
wb.Close SaveChanges:=False
End If
Next wb
End Sub
When you loop through worksheets, the loop variable is a reference to the actual sheet object, so any change you make (like ws.Range("A1") = "x") affects the real sheet.
For Each vs. For Next: Which to Use?
Use For Each when you need to process every item in a collection and don’t care about the index number. Use the traditional For i = 1 To N when you need the position, or when you need to modify the collection while looping (e.g., deleting rows).
Key differences:
- Speed:
For Eachis often faster because it doesn’t need to evaluate the collection’sCounteach iteration. - Safety:
For Eachis safer when you’re unsure how many items there are. - Flexibility:
For Nextlets you go backward (e.g.,For i = 10 To 1 Step -1), which is essential when deleting rows or items.
For example, to delete every other row, you’d need a For Next loop with a step, because For Each doesn’t allow a step.
Common Mistakes and How to Avoid Them
Even experienced VBA developers trip over these:
- Modifying the collection while looping: Adding or removing items (like deleting worksheets) during a
For Eachloop can cause errors or skipped items. If you must delete, loop backward with a numeric index. - Forgetting to declare the loop variable: Always use
Dim cell As Rangebefore the loop. If you omit it, VBA treats it as a Variant, which works but is slower and can cause type confusion. - Using
Selectinside the loop: Avoidcell.Selectorws.Activate—it slows down the macro and can cause screen flicker. Work directly with the object. - Assuming the loop runs at least once: If the collection is empty (e.g., no worksheets), the loop simply doesn’t run. That’s fine, but don’t expect a message.
Practical Examples: Working with Ranges
Here are three real-world patterns you’ll use often:
1. Sum values in a range:
Sub SumRange()
Dim cell As Range
Dim total As Double
For Each cell In Range("B2:B10")
If IsNumeric(cell.Value) Then
total = total + cell.Value
End If
Next cell
MsgBox "Total: " & total
End Sub
2. Highlight blank cells:
Sub HighlightBlanks()
Dim cell As Range
For Each cell In Range("A1:C20")
If cell.Value = "" Then
cell.Interior.Color = RGB(255, 255, 0) ' yellow
End If
Next cell
End Sub
3. Copy visible cells only: This is trickier because For Each will include hidden rows. Use SpecialCells(xlCellTypeVisible) to get only visible cells:
Sub CopyVisible()
Dim cell As Range
For Each cell In Range("A1:A10").SpecialCells(xlCellTypeVisible)
Debug.Print cell.Address
Next cell
End Sub
Remember: SpecialCells can throw an error if no visible cells exist, so wrap it in an On Error Resume Next or check first.
Frequently Asked Questions
Can I use For Each with a dictionary or collection object? Yes. VBA’s built-in Collection and the Scripting.Dictionary both support For Each. For a dictionary, the loop variable is the key, not the value. Example: For Each key In dict.Keys.
How do I exit a For Each loop early? Use Exit For. For example, if you find the first blank cell and want to stop:
For Each cell In Range("A1:A100")
If cell.Value = "" Then
MsgBox "First blank is " & cell.Address
Exit For
End If
Next cell
Why does my loop skip cells when I delete rows? Because For Each keeps a pointer to the next item, and deleting a row shifts the collection. Solution: loop from the bottom up using a numeric index: For i = 10 To 1 Step -1.
Can I loop through a range that is not contiguous? Yes, For Each works on a Range object that may consist of multiple areas. The loop visits each cell in each area, in order.
Is For Each available in Excel for Mac? Yes, VBA is supported in Excel for Mac, and For Each works identically. The only difference is that some keyboard shortcuts differ, but the code is the same.
Performance Tips and Best Practices
- Turn off screen updating: Put
Application.ScreenUpdating = Falsebefore the loop and set it back toTrueafter. This speeds up loops that modify many cells. - Use
Withblocks: If you’re setting multiple properties of the same object, wrap them in aWithblock to avoid repeated references. - Limit the range: Loop only over the used range, not entire columns. Use
Range("A1").CurrentRegionorUsedRangeto avoid iterating over 1,048,576 rows. - Declare variables with explicit types: This makes the code run faster and reduces errors.
Always save a copy of your workbook before running any macro that modifies data, because macros cannot be undone with Ctrl+Z. If a loop goes wrong, you could overwrite data permanently.
Related
- 6 Digit Random Number: How to Generate One
- Shortcut Command for Cut: Ctrl+X Explained
- Best Data Entry Sites: Top Picks for Real Work
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- VBA Open Excel File and Save as CSV with Working CodeYes. In VBA, open the workbook with Workbooks.Open, then call SaveAs with FileFormat:=xlCSVUTF8 to create a UTF-8 CSV…
- Excel Macro Recorder: How It Works and When to Use ItExcel’s Macro Recorder captures many worksheet actions and turns them into VBA code that you can run again…
- VBA AutoFilter Dynamic Range: A Reliable SetupTo apply VBA AutoFilter to a range that changes size, calculate the range’s last row (and, if needed,…
- VBA Code to Sort Excel Data by One or More ColumnsTo sort Excel rows with VBA, define the complete data range, add one or more sort keys, set…
- Microsoft VBA for Excel: What It Is and How It WorksMicrosoft VBA for Excel is the programming language built into desktop Excel for automating repetitive tasks, creating custom…
- VBA Convert Range to Number: 4 WaysTo convert a range of text-formatted numbers to actual numeric values in Excel VBA, use the Value property…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.