使用Excel VBA发布使用BuildingBlockEntry向Word文档添加水印
我目前正在尝试使用Excel VBA向Word文档添加水印。我已经能够从Word VBA执行此操作,并已将代码转换为excel以实现其他功能,但在特定行中出现错误。我认为在请求插入水印时,我需要更好地指向单词building block,但我不确定 错误是:oWord.Templates(strBBPath).BuildingBlockEntries(strBBName)行中的“请求的集合成员不存在”。插入其中:=oRng,RichText:=True 这是我的密码:使用Excel VBA发布使用BuildingBlockEntry向Word文档添加水印,vba,excel,ms-word,watermark,buildingblocks,Vba,Excel,Ms Word,Watermark,Buildingblocks,我目前正在尝试使用Excel VBA向Word文档添加水印。我已经能够从Word VBA执行此操作,并已将代码转换为excel以实现其他功能,但在特定行中出现错误。我认为在请求插入水印时,我需要更好地指向单词building block,但我不确定 错误是:oWord.Templates(strBBPath).BuildingBlockEntries(strBBName)行中的“请求的集合成员不存在”。插入其中:=oRng,RichText:=True 这是我的密码: Sub AddWa
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 Blocks\1033\14\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中运行此命令,则应为“运行时错误424-需要对象”。您无权访问Excel中的全局Word
对象,因此在此行中
…Excel不知道什么是Word
<模块顶部的code>Option Explicit将捕获此错误。您需要使用您的Word。应用程序对象:
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
我在这篇文章中找到了答案-
需要加载单词buildingblocks才能使用以下方法从中提取:oWord.Templates.LoadBuildingBlocks
谢谢大家的关注。:) 我感谢你澄清这一切,我已经做了这些更新。我仍然收到一个错误“运行时错误5941-请求的集合成员不存在”,我想知道是否需要以不同于excel的方式引用模板或构建块条目,但不确定。
Set oWord = New Word.Application