word interop /向页脚添加新字段会删除现有字段

时间:2013-11-20 20:00:50

标签: c# ms-word interop

我一直在使用互操作来编辑现有的word文档。我的问题是;我需要在文档页脚中添加一个新字段,并且我很惊讶,删除现有的页脚字段,因此只保留新添加的字段。没有关于它的明确文档,结果是相当意外的。以下是我的代码:

foreach (Microsoft.Office.Interop.Word.Section wordSection in wordDocument.Sections)
        {
            Microsoft.Office.Interop.Word.HeadersFooters footers = wordSection.Footers;
            foreach (HeaderFooter footer in footers)
            {
                footer.Range.Select();
                Field f = appWord.ActiveWindow.Selection.Fields.Add(appWord.ActiveWindow.Selection.Range);
                appWord.Selection.TypeText(footerText);
            }
        }

1 个答案:

答案 0 :(得分:1)

您所描述的是预期的行为,因为“.Add”不是“.Append”或“.InsertAfter”,您可能会合理地希望该字段将被添加到选择的末尾。如果在Word中选择一段文本并发出VBA命令

Selection.Fields.Add Selection.Range

你会看到很多相同的东西。

您需要做的是确定您需要插入字段的精确范围,并将其添加到那里。理想情况下,完全避免使用选择。因此,如果您需要在页脚的开头使用该字段,您可以从以下VBA示例开始并将其转换为C#(抱歉,我现在没有精力)。

Sub insertFieldAtStartOfSec1Footers()
Dim footer As HeaderFooter
Dim rng As Word.Range
For Each footer In ActiveDocument.Sections(1).Footers
  Set rng = footer.Range
  rng.Collapse wdCollapseStart
  ' Insert a simple SECTION field 
  rng.Fields.Add rng, WdFieldType.wdFieldEmpty, "SECTION", False
  Set rng = Nothing
Next
End Sub