O'Reilly logo

Writing Word Macros, Second Edition by Steven Roman PhD

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The For Each Loop

The 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:

	For Each ObjectVar In CollectionName
	   ' block of code goes here . . .
	Next ObjectVar

where 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:

	For Each object in Collection
	   ' code block here
	Next object

or:

	For 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.

The For Each statement can also be used to iterate through collections of non-object items. For instance, the FontNames collection contains ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required