2017-03-09 47 views
0

現在Excel VBAを使用してWord文書にウォーターマークを追加しようとしています。私はWord VBAからそうすることができ、他の機能を実装するためにコードを翻訳して、特定の行にエラーが発生しています。私はウォーターマークの挿入を要求するときにWordビルディングブロックを指し示す必要があると思っていますが、わかりません。Excel VBAを使用してBuildingBlockEntryを使用してWord文書にウォーターマークを追加する問題

エラーがラインから "コレクションの要求されたメンバーが存在しない" です。oWord.Templates(strBBPath).BuildingBlockEntries(strBBName).Insert:= oRng、リッチテキスト:ここで= 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 

答えて

1

あなたはどこか他のあなたのコード内の浮遊Word識別子を持っていない限り、あなたがその特定のエラーメッセージが表示されます理由はありません手掛かり。これをExcelで実行している場合は、とする必要があります。「実行時エラー424 - オブジェクトが必要です」。あなたは...この行のため、Excelで

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

をグローバルWordオブジェクトへのアクセス権を持っていない... ExcelはWordが何であるかわかりません。モジュールの上部にあるOption Explicitはこのエラーを検出していました。あなたのWord.Applicationオブジェクトを使用する必要があります、あなたは明らかに事前バインディングを使用していると述べた

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

を、そう宣言しoWord

Dim oWord As Word.Application 

...と使いNew代わりのCreateObject ... Word.Applicationとして:

Set oWord = New Word.Application 
+0

これらのすべてを明確にしていただき、ありがとうございます。これらの更新を行いました。私はまだ "実行時エラー5941 - コレクションの要求されたメンバーが存在しません"のエラーが表示されます私はテンプレートやビルドブロックのエントリをExcelから別の方法で参照する必要があるかどうかは分かりませんか? – Allen

関連する問題