471,071 Members | 1,325 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,071 software developers and data experts.

Replace text with bookmark in word document

Hi,
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.

Thanks,
Adam.
Nov 16 '05 #1
1 4854
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
Nov 16 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

reply views Thread by ingvald | last post: by
5 posts views Thread by Casey | last post: by
3 posts views Thread by gregpinero | last post: by
2 posts views Thread by Alan T | last post: by
reply views Thread by Alan T | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.