设置Range.Text而不破坏字段?

时间:2017-05-23 10:23:19

标签: c# ms-word vsto

我需要从Word文档页脚中删除一些文本,其中还包含字段(例如页码)。简单吧?

但是,当我更新范围中的文本时,它会破坏它包含的字段。例如,页码字段只是一个数字(而不是一个保持最新的字段)。

有没有办法在不影响其包含的字段的情况下更改范围内的文本?

这是我目前的代码:

string wordToRemove = "foo";            

foreach (Section section in doc.Sections)
{
    foreach (HeaderFooter footer in section.Footers)
    {
        if (footer.Range.Text.Contains(wordToRemove))
            footer.Range.Text = footer.Range.Text.Replace(wordToRemove, "");
    }
}

1 个答案:

答案 0 :(得分:3)

  

简单,对吧?

确实 - 只要您了解Find对象的Range 属性(?!):

//
// Summary:
//     Returns a Microsoft.Office.Interop.Word.Find object that contains the criteria
//     for a find operation.
Find Find { get; }

反过来提供了一个方便的Execute方法,有很多选项,更重要的是,它具有所需的非破坏性行为:

string wordToRemove = "foo";

foreach (Section section in doc.Sections)
{
    foreach (HeaderFooter footer in section.Footers)
    {
        footer.Range.Find.Execute(FindText: wordToRemove, ReplaceWith: "", Replace: WdReplace.wdReplaceAll);
    }
}