For Each loop is a variation on the
For loop that was designed to iterate through a collection of objects (as well as through elements in an array) and is generally much more efficient than using the traditional
For loop. The general syntax is:
CollectionName' block of code goes here . . . Next
ObjectVar is a variable of the same object type as the objects within the collection. The code block will execute once for each object in the collection.
To illustrate, here is how the earlier example that changes Heading 1 style to Heading 2 style would appear using a
For Each loop:
Dim para As Paragraph For each para in ActiveDocument.Paragraphs ' Change style from Heading 1 to Heading 2 If para.Style = "Heading 1" Then para.Style = "Heading 2" End If Next para
As you can see, this code is much more concise.
Thus, when iterating through a collection of objects, we have two choices:
Collection' code block here Next
i= 1 to
Collection.Count' code block here Next i
However, I must emphasize the point that the
For Each loop can be much faster than the
For loop when dealing with collections of Word objects. Thus, except for small collections, it is the preferred method. I will provide a rather dramatic example of this when I discuss an example related to the Style object.
For Each statement can also be used to iterate through collections of non-object items. For instance, the FontNames collection contains ...