NET Word Object Library Range Find.Execute infinite Loop

I am trying to find some text and italics part of it. I keep having infinite loop for big document but not small document. How can I fix it?
Dim wholeDoc As Word.Range= Globals.ThisDocument.Application.ActiveDocument.Range() 
With wholeDoc.Find
                .Text = "test"
                .MatchCase = True
                Do While .Execute()
                    Dim foundRange As Word.Range = Globals.ThisDocument.Application.ActiveDocument.Range(wholeDoc.Start + 1, wholeDoc.End - 1)

                    Try
                        foundRange.Italic = True
                       
                    Catch ex As Exception
                   

                    End Try

                Loop
            End With

        Next

Open in new window

xedge88Asked:
Who is Participating?
 
Miguel OzConnect With a Mentor Software EngineerCommented:
Previous code is not checking the found property.
Please modified code as follows:
        Dim wholeDoc As Word.Range = Globals.ThisDocument.Application.ActiveDocument.Range()
        Dim findDoc As Word.Find = findDoc
        findDoc.Text = "test"
        findDoc.MatchCase = True
        findDoc.Execute()
        While findDoc.Found
            Dim foundRange As Word.Range = Globals.ThisDocument.Application.ActiveDocument.Range(wholeDoc.Start + 1, wholeDoc.End - 1)
            Try
                foundRange.Italic = True
            Catch ex As Exception
            End Try
            findDoc.Execute()
        End While
0
 
GrahamSkanRetiredCommented:
I have modified your code to run as a Word macro, and can't reproduce the problem. How big does a document have to get before failing?

Incidentally, I note that there is a spurious Next (line 19), so I guess that the Do loop is nested in another loop. I trust that it is not this outer loop that is causing you a problem.

0
 
xedge88Author Commented:
Hi, please ignore the line 19 "Next", it was a typo.

I had a document that is 200 pages which I am getting the problem. I read thing like if any formatting was to be done inside the Do While, then this problem will occured, I do not kn how true is this.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.