0

I am trying to bookmark all the fields with text 'sample' in a word document. I need to bookmark all of them with the bookmark Name "fld_sample". I am using Microsoft.Office.Interop.Word API to do this programatically. The code below is sample code that I have tried from my end.

using Microsoft.Office.Interop.Word;
using System.Reflection; 

Object oTrue = true; Object oFalse = false;
Application oWord = new Application();
Document oWordDoc = new Document();
oWord.Visible = true;
Object oTemplatePath = @"string Path";

oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref      oMissing);

//selecting the range of text to bookmark.
Range rng = oWordDoc.Range(12, 18);

 oWordDoc.Bookmarks.Add("fld_sample", rng);

 //selecting the next range of text to bookmark with same name
 Range rng1 = oWordDoc.Range(102, 108);

 oWordDoc.Bookmarks.Add("fld_sample", rng1);

But the bookmark is only added for second range of values and not for first range of text. Can anyone help me with this code.

user1081802
  • 47
  • 1
  • 1
  • 6

1 Answers1

0

Each bookmark needs to have a unique name. Your second call effectively reassigns bookmark 'fld_sample'. If you want to have a set you can refer to in a loop in code, name subsequent bookmarks something like 'fld_sample2', 'fld_sample3' etc.

DaveE
  • 3,579
  • 28
  • 31
  • That wouldn't work in my case. My requirement is that, I need to bookmark all the occurances of word 'sample' in the entire word document with same name. so that, in my second use case I will use this bookmarked word document and replace all the bookmark with name 'fld_sample' with some other text provided by the user. – user1081802 Aug 13 '12 at 21:02
  • I get your *requirement*, but that's not how Word bookmarks *work*. You're gong to need to work out a programmable naming scheme and process the bookmarks in a loop. Or do a no-bookmark text replace. – DaveE Aug 17 '12 at 04:38