Word 自动化查找和替换不包括文本框 [英] Word Automation Find and Replace not including Text Boxes

查看:66
本文介绍了Word 自动化查找和替换不包括文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有文本框的 Word 文档.当我运行自动查找并替换主文档中的匹配项时,但不匹配文本框中的任何内容.我如何告诉查找和替换功能包含文本框.

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);

我怀疑我需要更改 range = objDoc.content 行.

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

推荐答案

有点乱,但对我有用:

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

namespace ConsoleApplication7
{
    class Program
    {
        static void Main()
        {
            const string documentLocation = @"C:	empFoo.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);
        }
    }
}

之前:

之后:

这篇关于Word 自动化查找和替换不包括文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆