0

在 Word 文档中搜索样式时,有时会在仅找到第一个匹配项后挂起样式搜索,并进入无限循环。这主要发生在表格中,即使稍后在同一单元格中出现。搜索文本时永远不会发生这种情况。那是一个错误吗?它是如何工作的?

Public Sub FindOccurences()
    On Error GoTo MyErrorHandler


    Dim i As Long: i = 0
    Dim findRange As Range
    Set findRange = ActiveDocument.Range

    With findRange.Find
        findRange.Find.ClearFormatting

        'findRange.Find.Text = "the" 'Never hangs searching for text
        findRange.Find.Style = ActiveDocument.Styles("text.10")

        Do While .Execute(Forward:=True) = True
            findRange.HighlightColorIndex = wdTurquoise
            i = i + 1

            DoEvents
        Loop
    End With

    MsgBox "Done. Found times: " & i

    Exit Sub

MyErrorHandler:
    MsgBox "FindOccurences" & vbCrLf & vbCrLf & "Err = " & Err.Number & vbCrLf & "Description: " & Err.Description
End Sub
4

1 回答 1

0

I tried this code and ended up with an infinite loop, even though my document does not have any tables. I think the problem is that the while loop condition you use is constructed for a linear search of the word document, and that styles are not searched in a linear fashion, but rather iterated through some type of collection data structure.

于 2012-04-24T19:34:32.097 回答