Microsoft Word Hangs During A Find Using Styles

Go To StackoverFlow.com

0

When searching for styles in a Word document, a search for styles sometimes hangs after finding only the first occurrence, and enters an endless loop. This happens mostly within tables, even if there are occurrences later in the same cell. It never happens when searching for text. Is that a bug? How is it worked around?

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
2012-04-05 15:58
by ForEachLoop


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-24 19:34
by alkematic
A corrupted link list? That would explain some things but how do work around this - ForEachLoop 2012-04-25 19:45
Ads