2017-10-24 9 views
0

2つの異なる配列を使用して2つの異なるデータポイントをワードドキュメント内の2つの異なるフィールドに入れたいと考えています。 1つの "For Each"ループを実行して、フィールドの1つを取り込むことができますが、2つの "For Each"ループを一緒に実行して、両方のフィールドにドキュメントを保存する前に実行する方法がわかりません。ここに私の現在のコードである:2つの "For Each"ループを一緒に使用する - Word VBA

Sub Numbering() 
' 
' Account Numbering and Naming Macro 
' 
' 
Dim Rng1 As Range 
Dim Rng2 As Range 

Dim AccountNumbers As Variant, AccountNumber As Variant 
    AccountNumbers = Array("20T5555", "20T3333", "20T8888", "20T1111") 

Dim AccountNames As Variant, AccountName As Variant 
    AccountNames = Array("Branch 1", "Branch 2", "Branch 3", "Branch 4") 

Set Rng1 = ActiveDocument.Bookmarks("AccountNumber").Range 
Set Rng2 = ActiveDocument.Bookmarks("AccountName").Range 

    For Each AccountNumber In AccountNumbers 

    AccountNumber1 = AccountNumber 
    Rng1.Delete 
    Rng1.Text = AccountNumber1 

      For Each AccountName In AccountNames 

      AccountName1 = AccountName 
      Rng2.Delete 
      Rng2.Text = AccountName1 

    ' Silent Save_to_PDF Macro 
    ' 
    ActiveDocument.ExportAsFixedFormat OutputFileName:= _ 
    Replace(ActiveDocument.FullName, "template.docx", Trim(AccountNumber1) & ".pdf"), _ 
    ExportFormat:=wdExportFormatPDF, OpenAfterExport:=True, OptimizeFor:= _ 
    wdExportOptimizeForPrint, Range:=wdExportAllDocument, Item:= _ 
    wdExportDocumentContent, IncludeDocProps:=False, KeepIRM:=True, _ 
    CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _ 
    BitmapMissingFonts:=True, UseISO19005_1:=False 

      Next AccountName 
    Next AccountNumber 

ActiveDocument.Save 

End Sub 

所望の結果は、第1の出力文書に他の内の1つのフィールドとブランチ1で20T5555を持っているだろう、など20T3333及び第二にブランチ2、

+0

通常、これは、[差し込み印刷]で行われている(https://support.office.com/en-us/article/Mail-merge-using - Excelスプレッドシート-858c7d7f-5cc0-4ba1-9a7b-0a948fa3d7d3)。しかし、あなたがそれを使用したくない場合でも、私はあなたの問題が何であるか分かりません。なぜなら、あなたは2つの 'each each'ループ(入れ子にされ、データ配列のデカルト結合を生成する)を持っているように見えるからです。別のタイプの結合が必要な場合、配列の 'lbound'から' ubound'までのインデックスを持つ 'for'ループを使います(それらの配列は同じ長さでなければなりません)。 – GSerg

+0

@GSerg私はVBAを使いこなすのがとても新しいです。ループを一緒に使用する方法を示すコードスニペットを投稿して、各パスで各配列の同じインデックス番号がドキュメントに挿入されるようにすることはできますか? –

+0

@GSerg私は自分の投稿に追加情報を追加しました。私はデカルト結合を望んでいません、インデックス1をインデックス1に、インデックス2をインデックス2に、そして同様に –

答えて

1

Forループは、同じインデックスを持つアイテムを取得するために使用することができます。

AccountNumbers = Array("20T5555", "20T3333", "20T8888", "20T1111") 
AccountNames = Array("Branch 1", "Branch 2", "Branch 3", "Branch 4") 

For i = 0 To Ubound(AccountNames) 
    Debug.Print AccountNumbers(i), AccountNames(i) 
Next i 
+0

AHに参加したいと思います。私はあなたを見つけました! ありがとう、ありがとう、ありがとう! –

関連する問題