VbaLoopsBeginner

For Each...Next

Iterates over each object or value in a collection-like structure.

Review the syntaxStudy the examplesOpen the coding app
For Each item In collection
    ' statements
Next item

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

Iterates over each object or value in a collection-like structure.

For Each is the natural looping pattern for worksheets, ranges, workbooks, shapes, and other VBA collections. It is often safer than index-based loops when you do not care about position and simply need to visit each object. Use index loops instead when you need direct row numbers or positional writes.

Quick reference

Syntax

For Each item In collection
    ' statements
Next item

See it in practice

Examples

1

Loop through worksheets

Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
    Debug.Print ws.Name
Next ws

For Each is ideal for workbook objects and other VBA collections.

Debug faster

Common Errors

1

Type mismatch

Cause: Using a loop variable whose type does not match the items in the collection.

Fix: Declare the loop variable using the expected object type or Variant where appropriate.

Runtime support

Compatibility

Excel desktop VBA

Source: Microsoft Learn Office VBA reference

Common questions

Frequently Asked Questions

Iterates over each object or value in a collection-like structure.

Type mismatch: Declare the loop variable using the expected object type or Variant where appropriate.