Word Automation Find and Replace not including Text Boxes

耗尽温柔 提交于 2019-12-18 05:06:12

问题


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.


回答1:


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:

After:




回答2:


This solution doesn't replace text within as TextBox in the Header.



来源:https://stackoverflow.com/questions/14256417/word-automation-find-and-replace-not-including-text-boxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!