I have a .doc Word document and there is a text in header. I want to find the word "MyWord" from the header and add a bookmark to it (bookmark is also called "MyWord"). At the moment the code I have is able to search in headers and footers, but I don't know how to select the word of interest. I used a string variable to load the text content of the header and I find the start and end of my word. However, when I select this range, the selection highlights a different area. Here is the code:
public static void AddBookmarkAnywhere(Microsoft.Office.Interop.Word.Application app, string findText, string bookmarkName)
{
var doc = app.ActiveDocument;
foreach (Microsoft.Office.Interop.Word.Range rngStory in doc.StoryRanges)
{
var internalRangeStory = rngStory;
do
{
AddBookmarkInStory(internalRangeStory, findText, bookmarkName);
try
{
switch (internalRangeStory.StoryType)
{
case Microsoft.Office.Interop.Word.WdStoryType.wdEvenPagesHeaderStory: // 6
case Microsoft.Office.Interop.Word.WdStoryType.wdPrimaryHeaderStory: // 7
case Microsoft.Office.Interop.Word.WdStoryType.wdEvenPagesFooterStory: // 8
case Microsoft.Office.Interop.Word.WdStoryType.wdPrimaryFooterStory: // 9
case Microsoft.Office.Interop.Word.WdStoryType.wdFirstPageHeaderStory: // 10
case Microsoft.Office.Interop.Word.WdStoryType.wdFirstPageFooterStory: // 11
if (internalRangeStory.ShapeRange.Count > 0)
{
foreach (Microsoft.Office.Interop.Word.Shape oShp in internalRangeStory.ShapeRange)
{
if (oShp.TextFrame.HasText != 0)
{
AddBookmarkInStory(oShp.TextFrame.TextRange, findText, bookmarkName);
}
}
}
break;
default:
break;
}
}
catch
{
MessageBox.Show("Some error in function FindReplaceAnywhere");
}
internalRangeStory = internalRangeStory.NextStoryRange;
}
while (internalRangeStory != null);
}
}
private static void AddBookmarkInStory(Microsoft.Office.Interop.Word.Range rngStory, string strSearch, string strBookmarkName)
{
string text = rngStory.Text;
int start = text.IndexOf(strSearch);
int end = start + strSearch.Length;
if(start >= 0)
{
rngStory.Start = start; // incorrect value
rngStory.End = start + strSearch.Length;
rngStory.Select();
rngStory.Bookmarks.Add(strBookmarkName, rngStory);
}
}