vbams-wordword-2010

word macro crashes when 'while' loop is executed


I have a VBA macro(Word2010) script to highlight all the text in italics. But when executed in large file say a document with more than 10 pages the Word get crashed. I have used the below code for this purpose.

Sub Italics_Highlight()
'
' test_italics_highlight_ Macro
'
'
    Application.ScreenUpdating = False
    Dim myString As Word.Range
    Set myString = ActiveDocument.Content
    With myString.Find
        .ClearFormatting
        .Text = ""
        .Font.Italic = True
        While .Execute
            myString.HighlightColorIndex = wdTurquoise
            myString.Collapse wdCollapseEnd
        Wend
    End With
    MsgBox "Thank you!"
End Sub

Could you please help to overcome this. Thanks for your help in advance.


Solution

  • You don't need to stop at each "found" and apply highlighting. You can do it as part of a Find/Replace:

    Sub testInfiniteLoop()
        Dim myString As word.Range
    
        Set myString = ActiveDocument.content
        Options.DefaultHighlightColorIndex = wdTurquoise
        With myString.Find
          .ClearFormatting
          .Text = ""
          .Font.Italic = True
          .Replacement.Text = ""
          .Replacement.Highlight = wdTurquoise
          .wrap = wdFindStop 'stop at the end of the document
          .Execute Replace:=wdReplaceAll
        End With
    End Sub