question

ZadumkinLev-1386 avatar image
0 Votes"
ZadumkinLev-1386 asked $$ANON_USER$$ commented

Interop.Word.Find - Infinite looping when found hyperlink

I came across an infinite loop problem when I used Find.Execute() in text that contains a hyperlink: the parent Range/Select object, from which the Find object was obtained, stops shifting to the next match.

 while (rng.Find.Found)
     {
         if (rng.Hyperlinks.Count > 0)
             test = rng.Start;
         if (rng.Text.Trim().Length > 0)
         {
             // do something 
         }
         rng.Find.Execute();
         if (rng.Start == test)
             MessageBox.Show("it will be infinite");
     }
dotnet-csharpoffice-word-itprooffice-vsto-com-dev
· 8
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.


Does it happen even if “// do something” does not do anything?

0 Votes 0 ·

yes, in my case it's just copying rng.Text in other variable without changes. So, it's probably do nothing.

0 Votes 0 ·

If possible, publish a sample Word file that demonstrates the problem, and a minimal code fragment (on OneDrive, etc.).

0 Votes 0 ·

You need to collapse the Found range to the start/end (as appropriate) of the hyperlink before the Find can resume.

0 Votes 0 ·

Yes, thanks. I already used this:

 if (rng.Hyperlinks.Count > 0)
 {
     // manually shift next
     rng.SetRange(rng.End, iniEnd);
 }
 // before 
 rng.Find.Execute();

where iniEnd is initial end of searched range.

0 Votes 0 ·

In VBA:

 Sub Demo()
 With ActiveDocument.Range
   With .Find
     .ClearFormatting
     .Replacement.ClearFormatting
     .Text = "Find String"
     .Replacement.Text = ""
     .Forward = True
     .Wrap = wdFindStop
   End With
   Do While .Find.Execute
     .HighlightColorIndex = wdBrightGreen
     .Collapse wdCollapseEnd
   Loop
 End With
 End Sub

Of course, the underlying issue may concern whatever your '// do something' is actually doing.

0 Votes 0 ·
Show more comments

1 Answer

DanielZhang-MSFT avatar image
0 Votes"
DanielZhang-MSFT answered ZadumkinLev-1386 commented

Hi ZadumkinLev-1386,
Please try to add the following code before the while statement loop:

 rng.Find.Execute();
 while (rng.Find.Found)
 {
   ...
 }

More details please refer to this document.
Best Regards,
Daniel Zhang


If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.







· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I used exactly this documentation when write my code, but there is a bug here, which I talked about - hyperlinks cause the loop to repeat indefinitely

0 Votes 0 ·