A VBA For Each loop runs a block of code once for every element in an array or collection, written as For Each element In group ... Next element. You do not need a counter or the item count, and Exit For leaves the loop early.
VBA For Each syntax
This is the form from Microsoft's reference for the statement:
For Each element In group
[statements]
[Exit For]
[statements]
Next [element]
The parts work like this:
- element is the variable that holds the current item on each pass.
- group is the name of an object collection or an array. The one exception is an array of user-defined types.
- statements are the lines that run for each item. They are optional.
The loop is entered only if the group has at least one element. After the last element, execution continues with the statement after Next. An empty collection therefore skips the loop without an error.
VBA For Each over cells in a range
The most common use is Excel's Range. The element is declared as Range, so each pass gives you one cell with all its properties:
Sub HighlightNegatives()
Dim cell As Range
For Each cell In Range("A1:A10")
If cell.Value < 0 Then
cell.Interior.Color = vbRed
End If
Next cell
End Sub
This runs against the active sheet. To make it independent of whichever sheet is active, qualify the range, for example Worksheets("Data").Range("A1:A10"). The same pattern works for any range, including a named range, as long as the element variable is a Range (or a Variant).
A second example counts how many cells in a range hold a value above a threshold. The counter is an ordinary variable that you manage yourself, because For Each does not provide one:
Sub CountAboveLimit()
Dim cell As Range
Dim matches As Long
For Each cell In Range("B2:B50")
If cell.Value > 100 Then matches = matches + 1
Next cell
Debug.Print "Cells above 100: " & matches
End Sub
Example output in the Immediate window (Ctrl+G in the VBA editor): Cells above 100: 7. The number depends on your data.
VBA For Each over worksheets
The Worksheets collection holds every worksheet in the workbook. According to Microsoft's Excel reference, Sheets is a wider collection: it contains all sheets, both chart sheets and worksheets. Pick Worksheets when you only want sheets that have cells:
Sub ListSheetNames()
Dim sheet As Worksheet
For Each sheet In Worksheets
Debug.Print sheet.Name
Next sheet
End Sub
Example output for a workbook with three tabs: Sheet1, Sheet2, Sheet3, one per line. If you loop over Sheets instead, the group can include chart sheets, which are not worksheets, so a Worksheet element variable is the wrong fit. If you need both kinds, declare the element as Object or Variant, which the documentation allows for collections.
Without a qualifier, Worksheets refers to the active workbook. If your macro lives in one workbook and processes another, qualify it with the workbook object so the loop does not run over the wrong file.
VBA For Each over an array
For arrays, the documentation says the element can only be a Variant. This matters because it catches people who declare the loop variable as String:
Sub ListFruit()
Dim fruit As Variant
For Each fruit In Array("apple", "pear", "plum")
Debug.Print fruit
Next fruit
End Sub
Example output: apple, pear, plum. Keep the loop variable a Variant and, if you need typed access, convert inside the body, for example CStr(fruit).
The loop variable is not the array slot itself, so do not rely on assigning to fruit to change the array. When you need to write back to the array, or you need the position of the item, use a counter loop instead; see VBA for loop: For...Next syntax and examples.
VBA For Each over a Collection
A Collection is a built-in VBA object. Microsoft describes it as an ordered set of items that can be referred to as a unit, and it states that the members do not have to share the same data type. The entire collection can be iterated with For Each. Create one with Dim X As New Collection and fill it with Add:
Sub ListCollection()
Dim cities As New Collection
Dim city As Variant
cities.Add "Oslo"
cities.Add "Lima"
cities.Add "Cairo"
For Each city In cities
Debug.Print city
Next city
Debug.Print "Items: " & cities.Count
End Sub
Example output: Oslo, Lima, Cairo, then Items: 3. The Collection object has three methods (Add, Item, Remove) and one property (Count). Item returns a member by position or by key.
One detail from the Collection page's own example is worth copying. Its cleanup loop removes members with MyClasses.Remove 1 on each pass, with the comment that collections are reindexed automatically, so the first member is removed every time. That is a counter loop, and it works because the first position is always refilled. Do not add or remove members of a collection from inside a For Each over that same collection. The documentation does not describe what happens in that case, so treat the behavior as undefined and collect the work first.
Element types: which one to declare
The rule on Microsoft's page differs by group type. This table sums it up:
| Group | Allowed element variable |
|---|---|
| Collection of objects (cells, sheets, your own Collection) | Variant, a generic object variable (Object), or a specific object type such as Range or Worksheet |
| Array | Variant only |
| Array of user-defined types | Not allowed at all |
A specific object type gives you IntelliSense for cell. or sheet. in the editor and catches typos at compile time, so prefer it for collections of objects.
Exit For
Any number of Exit For statements may appear in the loop. Microsoft notes that it is often used after testing a condition with If...Then, and that it transfers control to the statement immediately after Next. This loop stops at the first cell in A1:A100 that contains the text "Total" and reports its address:
Sub FindTotal()
Dim cell As Range
For Each cell In Range("A1:A100")
If cell.Value = "Total" Then
Debug.Print "Found at " & cell.Address
Exit For
End If
Next cell
End Sub
Example output: Found at $A$42. The Microsoft example for the statement follows the same shape: it searches every element of a collection for the string "Hello", sets a flag and exits.
Nested For Each loops
You can nest one For Each inside another. The one rule in the documentation is that each loop's element variable must be unique. Here an outer loop walks the worksheets and an inner loop walks a fixed range on each:
Sub CountFilledCells()
Dim sheet As Worksheet
Dim cell As Range
Dim filled As Long
For Each sheet In Worksheets
For Each cell In sheet.Range("A1:C10")
If Not IsEmpty(cell.Value) Then filled = filled + 1
Next cell
Next sheet
Debug.Print "Filled cells: " & filled
End Sub
Writing the element name after Next is optional. If you omit it, execution continues as if it were included. Keep it anyway: in nested blocks it shows which loop each Next closes. If a Next is met before its matching For, VBA raises an error.
For Each or For...Next?
- Use For Each when you want every item and do not care about its position: cells, sheets, shapes, collection members.
- Use For...Next when you need the index, need to step by more than 1, need to count backwards, or need to change values inside an array.
If you also script outside Office, the same idea exists in other languages. For a comparison, see PowerShell for loop and foreach examples.
Common mistakes
- Declaring the element of an array loop as a typed variable. It has to be
Variant. - Looping over
Sheetswith aWorksheetvariable. Chart sheets are inSheetsbut not inWorksheets. - Reusing one element variable in nested loops. Each loop needs its own.
- Using For Each on an array of user-defined types. It is not supported. Switch to an indexed loop.
- Expecting changes to the element variable to update an array. Write through the index instead.
Frequently asked questions
- What is the syntax of For Each in VBA?
- For Each element In group, then the statements to repeat, then Next [element]. The group is an array or a collection. The loop body runs once per element, and only if the group has at least one element.
- Why does For Each over an array need a Variant?
- Microsoft's documentation says that for arrays the element variable can only be a Variant. For collections the element can be a Variant, a generic object variable or a specific object variable, such as Range or Worksheet.
- Can I use For Each on an array of user-defined types?
- No. The documentation excludes arrays of user-defined types, because a Variant cannot contain a user-defined type. Use a For...Next loop with an index instead.
- How do I stop a For Each loop early?
- Put Exit For inside the loop, usually in an If...Then block. Control jumps to the statement after Next. In nested loops it leaves only the loop it is written in.
- What is the difference between Worksheets and Sheets in a For Each loop?
- Per Microsoft's Excel reference, Sheets contains every sheet in a workbook, both chart sheets and worksheets, while Worksheets contains only worksheets. Looping over Worksheets avoids chart sheets.