【发布时间】:2017-03-10 22:53:34
【问题描述】:
我目前正在尝试使用 Excel VBA 向 Word 文档添加水印。我已经能够从 Word VBA 执行此操作,并将代码转换为 excel 以实现其他功能,并且在特定行上出现错误。我相信在请求插入水印时我需要更好地指向 Word 构建块,但我不确定。
错误是来自以下行的“请求的集合成员不存在”: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 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
【问题讨论】:
标签: vba excel ms-word watermark buildingblocks