WordWriter search and replace in Word textboxes

Problem

When trying to use SearchAndReplace with a Word document that has text in a Word textbox or shape, the text doesn’t get replaced.

Solution

Unfortunately, WordApplication does not recognize the shape or textbox objects and so they will not be included in the set of elements parsed by the code above. The full list of elements recognized by WordApplication is outlined in this article.

Using WordTemplate to replace text

One possible workaround is to use the WordTemplate object for text replacement instead of SearchAndReplace. When WordTemplate processes a template, it largely ignores where the merge fields are located.

This means if there is text in a shape or textbox that needs to be replaced, the original text can be placed in a merge field and then WordTemplate can populate the merge field with the new text. For example, the code below looks through a Word document for mergefields marked <> an populates them with the value “REPLACED TEXT”. Then passes the processed template to the WordApplication object.

//Start with the WordTemplate object
//Template contains merge fields named "REPLACE"
wt.Open(Page.MapPath("\templates\TextBoxTemplate.doc"));
Object[] values = {"REPLACED TEXT"};
String[] names = {"REPLACE"};
wt.SetDataSource(values, names, "DataSource");
wt.Process();
Document doc = wapp.Open(wt);
//...Other WordApplication code here...
wapp.Save(doc, Page.Response, "TextBoxTemplate.doc", False);

For more information about WordTemplate and mergefields, please refer to our WordTemplate tutorials.

Related posts: