Jammy
Jammy

Reputation: 789

Word Automation Find and Replace not including Text Boxes

I have a word document which has a text box. When i run an automated find and replace its matching in the main document, but not match anything in the Text Box. How do i tell the find and replace function to include Text Boxes.

Word.Range range = objDoc.Content;

object findtext = Field;
object findreplacement = Value;
object findwrap = WdFindWrap.wdFindContinue;
object findreplace = WdReplace.wdReplaceAll;

range.Find.Execute(findtext, missing, missing, missing, missing, missing, missing, findwrap, missing, findreplacement, findreplace);

I suspect i need to change the range = objDoc.content line.

Upvotes: 6

Views: 9554

Answers (1)

JMK
JMK

Reputation: 28069

Slightly messy but this worked for me:

using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Word;

namespace ConsoleApplication7
{
    class Program
    {
        static void Main()
        {
            const string documentLocation = @"C:\temp\Foo.docx";
            const string findText = "Foobar";
            const string replaceText = "Woo";

            FindReplace(documentLocation, findText, replaceText);
        }

        private static void FindReplace(string documentLocation, string findText, string replaceText)
        {
            var app = new Application();
            var doc = app.Documents.Open(documentLocation);

            var range = doc.Range();

            range.Find.Execute(FindText: findText, Replace: WdReplace.wdReplaceAll, ReplaceWith: replaceText);

            var shapes = doc.Shapes;

            foreach (Shape shape in shapes)
            {
                var initialText = shape.TextFrame.TextRange.Text;
                var resultingText = initialText.Replace(findText, replaceText);
                shape.TextFrame.TextRange.Text = resultingText;
            }

            doc.Save();
            doc.Close();

            Marshal.ReleaseComObject(app);
        }
    }
}

Before:

Before

After:

After

Upvotes: 10

Related Questions