无法使用 VBA 在一批 word 文档的 header 中添加 table

Unable to add a table in the header of a batch of word documents using VBA

我正在尝试编写一个宏来打开特定文件夹中的 .docx 文件,删除 header 的内容,然后将 table 插入 header 和finally - 保存并关闭文档,以便按顺序移动到下一个文档。一切正常 - 除了它试图创建 table 的行。我的代码如下:

Sub BatchAddTableToHeaders()

    Dim wrd As Word.Application
    
    Set wrd = CreateObject("word.application")
    wrd.Visible = True
    FName = Dir("C:\MyFolder\*.docx")
    
    Do While (FName <> "")
        With wrd
            ' Open the next document in the folder
            .Documents.Open ("C:\MyFolder\" & FName)
            
            ' select the header, delete it and then insert a table
            .ActiveWindow.ActivePane.View.SeekView = wdSeekPrimaryHeader
            With .Selection
                .WholeStory
                .Delete
                .Tables.Add Range:=Selection.Range, NumRows:=1, NumColumns:=3, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitFixed
            End With
            
            .ActiveDocument.Save
            .ActiveDocument.Close
            
        End With
        FName = Dir
    Loop
    Set wrd = Nothing
End Sub

我收到的错误如下:

Run-time 错误 '-2147023170 (800706be)':

自动化错误

远程过程调用失败。

奇怪的是,只要我不试图打开和运行通过一批文件,它就会很乐意地在header中插入一个table。以下宏工作得很好:

Sub InsertTableIntoCurrentDocumentHeader()
    ActiveWindow.ActivePane.View.SeekView = wdSeekPrimaryHeader
    With Selection
        .WholeStory
        .Delete
        .Tables.Add Range:=Selection.Range, NumRows:=1, NumColumns:=3, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitFixed
    End With
End Sub

是否有人能够提供一些见解来解释为什么我的 'batch header' 宏失败了?

例如:

Sub BatchAddTableToHeaders()
Dim wdApp As New Word.Application, wdDoc As Word.Document, FName
FName = Dir("C:\MyFolder\*.docx")
With wdApp
  .Visible = False
  Do While (FName <> "")
    ' Open the next document in the folder
    Set wdDoc = .Documents.Open(FileName:="C:\MyFolder\" & FName, AddToRecentFiles:=False)
    With wdDoc
      With .Sections.First.Headers(wdHeaderFooterPrimary).Range
        .Text = vbNullString
        .Tables.Add Range:=.Duplicate, NumRows:=1, NumColumns:=3, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitFixed
      End With
      .Close SaveChanges:=True
    End With
    FName = Dir
  Loop
  .Quit
End With
Set wdDoc = Nothing: Set wdApp = Nothing
End Sub