There are several different ways you can loop on the elements of a collection. However, the recommended method for looping on a collection is to use the For Each...Next loop. In this structure, Visual Basic repeats a block of statements for each object in a collection. The following example displays the name of each document in the Documents collection.
For Each aDoc In Documents
MsgBox aDoc.Name
Next aDoc
Instead of displaying each element name in a message box, you can use an array to store the information. This example uses the aMarks()
array to store the name of each bookmark contained in the active document.
If ActiveDocument.Bookmarks.Count >= 1 Then
ReDim aMarks(ActiveDocument.Bookmarks.Count - 1)
i = 0
For Each aBookmark In ActiveDocument.Bookmarks
aMarks(i) = aBookmark.Name
i = i + 1
Next aBookmark
End If
You can loop through a collection to conditionally perform a task on members of the collection. For example, the following example updates the DATE fields in the active document.
For Each aField In ActiveDocument.Fields
If InStr(1, aField.Code, "Date", 1) Then aField.Update
Next aField
You can loop through a collection to determine if an element exists. For example, the following example displays a message if an AutoText entry named "temp" is part of the AutoTextEntries collection.
For Each aEntry In ActiveDocument.AttachedTemplate.AutoTextEntries
If aEntry.Name = "temp" Then _
MsgBox "temp AutoText entry exists"
Next aEntry