Jam*_*mmy 4 c# ms-word office-interop
我有一个word文档,其中有一个文本框.当我运行自动查找并替换主文档中的匹配,但不匹配文本框中的任何内容.我如何告诉查找和替换功能包括文本框.
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);
Run Code Online (Sandbox Code Playgroud)
我怀疑我需要更改range = objDoc.content行.
稍微凌乱,但这对我有用:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
之前:

后:
