For Each...Next

A For Each...Next loop is similar to a For...Next loop, except that it repeats a group of statements for each element in a collection of objects or in an array, instead of repeating the statements a specified number of times. This is especially useful if you don't know how many elements are in a collection, or if the contents of the collection might change as your procedure runs.

For Each element In group
statements
Next element

When Visual Basic runs a For Each...Next loop, it follows these steps:

1. It defines element as naming the first element in group (provided that there is at least one element).

2. It runs the statements.

3. It tests to see whether element is the last element in group. If so, Visual Basic exits the loop.

4. It defines element as naming the next element in group.

5. It repeats steps 2 through 4.

Keep the following restrictions in mind when using the For Each...Next statement:

The following example examines each cell in the current region for cell A1 on the worksheet named "sheet3" and deletes the cell if its value is less than -1.


For Each c In Worksheets("sheet3").Range("a1").CurrentRegion.Cells
    If c.Value < -1 Then c.Delete
Next c

For more information about collections and more examples of the For Each...Next statement, see Chapter 4, "Objects and Collections."

Note

The variable name after the Next statement is optional, but it can make your code easier to read, especially if you have several nested For loops.