【问题标题】:Word footer text doesn't update after replacement替换后Word页脚文本不更新
【发布时间】:2013-01-30 16:11:27
【问题描述】:

我正在尝试替换页脚中的部分文本。我正在使用 Range.Find 查找文本并替换它。在调试过程中,我设置了一些断点,以便在更改前后检查页脚的 Range.Text。它似乎在做它的工作。当我在 Locals 窗口中检查 Rang.Text 时,文本会按照我希望的方式更改。问题是它不更新文档。

当我第二次尝试时,Range.Text 仍然有我所做的更改,但它不会更新文档。

我已经尝试对文档的主体执行此操作,并且效果很好。我不确定我在这里缺少什么。

我正在对一些已保存的文档进行尝试。我必须取消对页脚的保护,以便在我尝试查找和替换文本时不会出现异常。

有人知道我是否缺少某种安全措施吗?

这是我的代码:

Word.Range docRange = currentDoc.Sections[1].Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
docRange.Find.ClearFormatting();
docRange.Find.Text = find;
docRange.Find.Replacement.ClearFormatting();
docRange.Find.Replacement.Text = replace;

object replaceAll = Word.WdReplace.WdReplaceAll;
docRange.Find.Execute(Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                      Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
                      ref replaceAll, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

如果您需要更多代码,请告诉我。

编辑:我尝试将页脚移动到新文档,保存它,然后使用调试器打开新文档,它似乎可以正常使用新文档。仍然 但不适用于原始文档。

【问题讨论】:

    标签: c# replace ms-word vsto footer


    【解决方案1】:

    我能够解决我的问题。我不太确定实际问题是什么,但我的猜测是页脚的格式非常奇怪。所以我决定更改代码以遍历页脚部分中的每个页脚,这似乎解决了我的问题。

    这是我为其他人更改的代码,希望对您有所帮助:

    foreach (Word.Section wordSection in currentDoc.Sections)
    {
        foreach (Word.HeaderFooter wordFooter in wordSection.Footers)
        {
            Word.Range docRange = wordFooter.Range; 
    
            docRange.Find.ClearFormatting();
            docRange.Find.Text = find;
            docRange.Find.Replacement.ClearFormatting();
            docRange.Find.Replacement.Text = replace;
    
            object replaceAll = Word.WdReplace.wdReplaceAll;
            docRange.Find.Execute(Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                      Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
                      ref replaceAll, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        }
    }
    

    如果有人能暗示为什么有必要进行这些循环,那将会很有帮助。

    【讨论】:

      猜你喜欢
      • 2015-07-09
      • 2018-02-12
      • 2019-05-20
      • 1970-01-01
      • 2021-10-03
      • 2019-08-27
      • 2019-12-12
      • 2016-01-26
      • 2021-03-13
      相关资源
      最近更新 更多