2017-03-09 106 views
0

我目前正在尝试使用Excel VBA向Word文档添加水印。我已经能够从Word VBA中完成这些工作,并将代码翻译成excel来实现其他功能,并且在特定的行上发生错误。我相信在请求插入水印时,我需要更好地指向Word Building Block,但我不确定。使用Excel VBA将Watermark添加到Word文档使用BuildingBlockEntry的问题

的错误是 “集合的请求的成员不存在” 从线路:oWord.Templates(strBBPath).BuildingBlockEntries(strBBName).Insert其中:= ORNG,富文本:=真

这里是我的代码:

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 

回答

1

不知道为什么你得到该错误消息,除非你有一个流浪Word标识别的地方在你的代码。如果您在Excel中运行此项,则应为为“运行时错误424 - 所需对象”。您没有访问Excel中的全球Word对象,所以在这条线......

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

... Excel有不知道什么是WordOption Explicit位于模块的顶部会发生此错误。您需要使用您的Word.Application对象:

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

也就是说,你显然是在利用早期绑定,所以宣布oWordWord.Application ...

Dim oWord As Word.Application 

...和使用New,而不是CreateObject

Set oWord = New Word.Application 
+0

我很感谢你澄清所有这一切,我已经做出了这些更新。我仍然收到错误“运行时错误5941 - 请求的收集成员不存在”我想知道是否需要以不同于Excel的方式引用模板或构建块条目,但我不确定。 – Allen