I am trying to create a program which searches in a Word doc for a certain word and adds a hyperlink to that word.
I can do the code to search for the word (using a FindandReplace
), and can work out how to add a hyperlink to a word doc, but I cannot work out how to hyperlink the word I searched for. I think its because I need to define the word I searched for as a Range.
My code so far is:
using System;
using Microsoft.Office.Interop.Word;
using Word = Microsoft.Office.Interop.Word;
using Color = Microsoft.Office.Interop.Word.WdColor;
...
private void button2_Click(object sender, EventArgs e)
{
// open word doc
object fileName = openFileDialog1.FileName;
object readOnly = false;
object isVisible = true;
var applicationWord = new Microsoft.Office.Interop.Word.Application();
applicationWord.Visible = true;
Microsoft.Office.Interop.Word.Document doc = applicationWord.Documents.Open(openFileDialog1.FileName, ReadOnly: false, Visible: true);
//using FindAndReplace
Word.Find fnd = applicationWord.ActiveWindow.Selection.Find;
fnd.ClearFormatting();
fnd.Replacement.ClearFormatting();
fnd.Forward = true;
fnd.Wrap = Word.WdFindWrap.wdFindContinue;
fnd.MatchCase = true;
fnd.MatchWholeWord = true;
fnd.Text = "Qwe";
fnd.Replacement.Text = "Qwe";
fnd.Execute(Replace: Word.WdReplace.wdReplaceAll);
Word.Hyperlinks hyp = doc.Hyperlinks;
object myRange = applicationWord.Selection.Range;
object linkAddr = textBox1.Text;
object linkSubAddr = textBox2.Text;
Microsoft.Office.Interop.Word.Hyperlink myLink = hyp.Add(myRange, ref linkAddr, ref linkSubAddr);
}
I just can't get the hyperlink to be applied to the Word I searched for