在 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