adam lital wrote:
I have word document and i want to replace a specific text with a bookmark
using code.
Example:
in the document i have the text [ClientName] and i want to replace this to a
bookmark called ClientName.
Hi Adam,
the following code worked for me,
tested with Word 2003 and PIAs installed.
using Microsoft.Office.Interop.Word;
[...]
private void button1_Click(object sender, System.EventArgs e)
{
//C# cannnot handle optional params
object miss = Type.Missing;
//new Word.Application
ApplicationClass app = new ApplicationClass();
//File we want to open
//Has to be an object for C#
object fileName = @"C:\\test.doc";
//open the file, use VB.NET in the future ;-)
DocumentClass doc = (DocumentClass) app.Documents.Open(ref fileName,
ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss,
ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss,
ref miss);
//make Word visible
app.Visible = true;
Selection sel = app.Selection;
do //for every match found in the document
{
//formats don't matter
sel.Find.ClearFormatting();
//we have to use Wildcards
sel.Find.MatchWildcards = true;
//seach everything that starts with "[" then something in between
//and then "]"
sel.Find.Text = @"\[?@\]";
//search direction
sel.Find.Forward = true;
//let's go!
sel.Find.Execute(ref miss, ref miss, ref miss, ref miss, ref miss,
ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss,
ref miss, ref miss, ref miss);
//delete the brackets
string selText = sel.Text.Replace("[", string.Empty);
selText = selText.Replace("]", string.Empty);
//add bookmark with the text in brackets
sel.Bookmarks.Add(selText, ref miss);
} while (sel.Find.Found == true); //go on
}
Cheers
Arne Janning