使用 Interop 更改某些 word 文档的脚注编号失败

Changing Footnote numbering fails for some word documents with Interop

我将以下代码与安装的 Word 2016 一起使用,引用 Microsoft Word 16.0 Object Library

private void RefreshFootnoteNumbering(FileManagement.FileManager FileManager)
{
    Console.WriteLine(DateTime.Now.ToString() + " Refreshing footnotes DOCX");

    // Opening and saving in word generates the required element
    var Word = GetWordApp();
    try
    {
        var DocxPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.ChangeExtension(FileManager.HtmlFileLocation, "docx"));
        Console.WriteLine(DateTime.Now.ToString() + "\tOpening document");
        var Doc = GetWordDoc(Word, DocxPath);
        try
        {
            // Fails on these lines below (both cause the same exception)
            Doc.Footnotes.NumberingRule = InteropWord.WdNumberingRule.wdRestartPage;
            Doc.Footnotes.Location = InteropWord.WdFootnoteLocation.wdBottomOfPage;

            Doc.SaveAs2(DocxPath, InteropWord.WdSaveFormat.wdFormatXMLDocument, AddToRecentFiles: false, EmbedTrueTypeFonts: true);
        }
        finally
        {
            Doc.Close();
            Doc = null;
        }
    }
    finally
    {
        Word.Quit();
        Word = null;
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

这适用于大多数文档,但对于某些文档我会遇到以下异常:

System.Runtime.InteropServices.COMException was unhandled
  ErrorCode=-2146823680
  HResult=-2146823680
  HelpLink=wdmain11.chm#37376
  Message=Value out of range
  Source=Microsoft Word
  StackTrace:
       at Microsoft.Office.Interop.Word.Footnotes.set_NumberingRule(WdNumberingRule prop)

其他互操作函数(iterating/manipulating 字段、部分等)工作正常,似乎只是以这种方式更改脚注有问题。从 Word 本身改变它们工作正常。

有没有人遇到过这个问题?有任何解决方法或替代方案吗?


我试过录制一个宏,它给出了这个 VBA 代码:

With ActiveDocument.Range(Start:=ActiveDocument.Content.Start, End:= _
    ActiveDocument.Content.End).FootnoteOptions
    .Location = wdBottomOfPage
    .NumberingRule = wdRestartContinuous
    .StartingNumber = 1
    .NumberStyle = wdNoteNumberStyleArabic
    .NumberingRule = wdRestartPage
    .LayoutColumns = 0
End With

如果我 运行 这个宏,我会在 .Location 行得到相同的错误(值超出范围,错误号 4608),无论我是否 运行 来自调试器,或者只查看宏 -> 运行.

我还尝试将 VBA 翻译成 C# 代码:

var Options = Doc.Range(Doc.Content.Start, Doc.Content.End).FootnoteOptions;

Options.Location = InteropWord.WdFootnoteLocation.wdBottomOfPage;
Options.NumberingRule = InteropWord.WdNumberingRule.wdRestartPage;

然而,这给出了同样的错误。

仍然不确定确切原因(可能是在我的代码中创建了不同的部分);仍然不清楚为什么它在 word 记录宏时起作用,但在 运行 时不起作用。

无论如何,我设法将 C# 代码更改为以下内容,这似乎可以完成工作并且确实有效!

foreach(InteropWord.Footnote FootNote in Doc.Footnotes)
{
    FootNote.Reference.FootnoteOptions.NumberingRule = InteropWord.WdNumberingRule.wdRestartPage;
    FootNote.Reference.FootnoteOptions.Location = InteropWord.WdFootnoteLocation.wdBottomOfPage;
}