使用 Excel VBA 使用 BuildingBlockEntry 将水印添加到 Word 文档的问题

Issue using Excel VBA to add Watermark to Word Document using BuildingBlockEntry

我目前正在尝试使用 Excel VBA 为 Word 文档添加水印。我已经能够从 Word VBA 执行此操作并将代码转换为 excel 以实现其他功能,但在特定行上出现错误。我相信在请求插入水印时我需要更好地指向 Word 构建块,但我不确定。

错误是 "The requested member of the collection does not exist" 来自以下行:oWord.Templates(strBBPath).BuildingBlockEntries(strBBName).Insert Where:=oRng, RichText:=True

这是我的代码:

    Sub AddWatermark()
     Dim oWord as Word.Application
     Dim oDoc As Word.Document
     Dim oSection As Word.section
     Dim oHeader As Word.HeaderFooter
     Dim oRng As Word.Range
     Dim strName As String
     Dim strPath As String
     Dim strBBPath As String
     Const strBBName As String = "SAMPLE 1" 'The building block name that you want to insert

     strBBPath = "C:\Users\" & (Environ$("Username")) & "\AppData\Roaming\Microsoft\Document Building Blocks33\Built-In Building Blocks.dotx"

               Dim lngCount As Long

               ' Open the file dialog
               With Application.FileDialog(msoFileDialogOpen)
                   .AllowMultiSelect = True
                   .Show

                   ' Display paths of each file selected
                   For lngCount = 1 To .SelectedItems.Count
                        Set oWord = New Word.Application
                        strPath = .SelectedItems(lngCount)
                        Set oDoc = oWord.Documents.Open(strPath)
                   Next lngCount
               End With

     'oDoc.Save 'save the document
     strName = oDoc.FullName 'Record the document name
     oWord.Visible = True

     'Address each section
     For Each oSection In oDoc.Sections
         'Address each header in the section
         For Each oHeader In oSection.Headers

             Set oRng = oHeader.Range
             oRng.Start = oRng.End 'set the range to the end of the header
             'Insert the built-in building block
             oWord.Templates(strBBPath).BuildingBlockEntries(strBBName).Insert Where:=oRng, RichText:=True

         Next oHeader
     Next oSection

     End Sub

除非代码中的其他地方有一个杂散的 Word 标识符,否则不知道为什么会收到该特定错误消息。如果你是 运行 Excel 中的这个,它 应该 是 "Run-time error 424 - Object required"。您无权访问 Excel 中的全局 Word 对象,因此在这一行中...

Word.Application.Templates(strBBPath).BuildingBlockEntries(strBBName).Insert Where:=oRng, RichText:=True

...Excel 不知道 Word 是什么。 Option Explicit 在你模块的顶部会发现这个错误。您需要使用 Word.Application 对象:

oWord.Templates(strBBPath).BuildingBlockEntries(strBBName).Insert Where:=oRng, RichText:=True

就是说,您显然在使用早期绑定,所以将 oWord 声明为 Word.Application...

Dim oWord As Word.Application

...并使用 New 而不是 CreateObject:

Set oWord = New Word.Application

我从这个 post - https://answers.microsoft.com/en-us/msoffice/forum/msoffice_word-mso_other/run-time-error-5941-not-always-but-annoyingly/b95ec1db-6928-4d87-b799-52d4f1c01f08

中找到了答案

需要加载 Word 构建块才能使用此方法提取:oWord.Templates.LoadBuildingBlocks

感谢所有看过的人。 :)