2017-03-09 128 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

相關問題