rafatic
rafatic

Reputation: 223

Word - Replace text by hyperlinks

I am working on a MS-Word addin that reads the content of a document and replaces every occurence of a specific word by a hyperlink.

So far, I came up with this working algorithm.

// Initializes the Find parameters
searchRange.Find.ClearFormatting();
searchRange.Find.Forward = true;
searchRange.Find.Text = "foo";
do
{  
      searchRange.Find.Execute(Wrap: Word.WdFindWrap.wdFindStop);

      if (searchRange.Find.Found)
      {
           // Creates a Hyperlink at the found location in the current document 
           this.WordDocument.Hyperlinks.Add(searchRange, externalLink, link, "bar");
      }
      searchRange.Find.Execute(Wrap: Word.WdFindWrap.wdFindStop);
} while (searchRange.Find.Found);

This code works, however, it can be slow on bigger documents. Thus, instead of adding hyperlinks one by one, I wanted to simply to use the Find.Replacement object and with the WdReplace.ReplaceAllproperty.

However, I cannot manage to replace my search result by a Hyperlink.

Is there a way to replace a piece of text by a hyperlink using the Replacemethod ? In other words, I'd like to find a way to do this :

Find.Replacement.Text = new Hyperlink(...);

On an other side, I've seen that, by hitting Alt + F9in Word, we can see hyperlinks as code. The code looks like this : { HYPERLINK \l "link" \o "Caption" }

Another solution would be to be able to set the text replacement as that string and make Word interpret it and thus, create the link.

Thanks for reading.

Upvotes: 0

Views: 870

Answers (1)

Chris
Chris

Reputation: 3519

As far as I know, fields can only be inserted programmatically, or by using CTRL-F9. There are two possible reasons for this that I see:

  • They are not simple text. They have two ranges, the Code and the Result, only one of which is displayed at any time.
  • How else would a user insert text that looks like a code but is not supposed to be one, unless there was a special mechanism to create one?

Upvotes: 1

Related Questions