循环遍历一个集合

   

有多种不同的方法可在集合中的所有元素间进行循环。但是,推荐使用 For Each...Next 循环语句在集合中进行循环。在该结构中,Visual Basic 对集合中的每个对象重复执行同一组语句。下列显示 Documents 集合中每个文档的名称。

Sub LoopThroughOpenDocuments()
    Dim docOpen As Document

    For Each docOpen In Documents
        MsgBox docOpen.Name
    Next docOpen
End Sub

可以不用消息框显示每个元素的名称,而使用数组存储这些信息。该示例使用数组存储活动文档中包含的所有书签的名称。

Sub LoopThroughBookmarks()
    Dim bkMark As Bookmark
    Dim strMarks() As String
    Dim intCount As Integer

    If ActiveDocument.Bookmarks.Count > 0 Then
        ReDim strMarks(ActiveDocument.Bookmarks.Count - 1)
        intCount = 0
        For Each bkMark In ActiveDocument.Bookmarks
            strMarks(intCount) = bkMark.Name
            intCount = intCount + 1
        Next bkMark
    End If
End Sub

可循环遍历集合,有条件地对集合成员执行某项任务。例如,下列示例更新活动文档中的 DATE 域。

Sub UpdateDateFields()
    Dim fldDate As Field

    For Each fldDate In ActiveDocument.Fields
        If InStr(1, fldDate.Code, "Date", 1) Then fldDate.Update
    Next fldDate
End Sub

可以循环遍历一个集合来确定某元素是否存在。例如,如果名为“Filename”的词条是 AutoTextEntries 集合中的一部分,则以下示例显示一条消息。

Sub FindAutoTextEntry()
    Dim atxtEntry As AutoTextEntry

    For Each atxtEntry In ActiveDocument.AttachedTemplate.AutoTextEntries
        If atxtEntry.Name = "Filename" Then _
            MsgBox "The Filename AutoText entry exists."
    Next atxtEntry
End Sub