Excel VBA | 複数マスタ結合(3〜5マスタ)にも対応したプロ用汎用テンプレ

Excel VBA VBA
スポンサーリンク

ここでは 「複数マスタ結合(3〜5マスタ)対応・配列 × Dictionary × 自動範囲 × 高速書き戻し」プロ用汎用テンプレート を作ります。
業務でよくあるパターン:

  • メイン表に複数マスタから情報を結合したい
  • 行数は数万~数十万、マスタも数万行
  • VLOOKUP を何回も使うと遅すぎる

→ このテンプレは 数十万行でも 1 秒前後で処理可能


複数マスタ結合プロ用テンプレ(汎用版)

Sub MultiMasterJoin()

    Dim ws As Worksheet
    Dim LastRow As Long, LastCol As Long
    Dim Data As Variant
    Dim r As Long, i As Long

    Dim MasterSheets As Variant
    Dim MasterDicts() As Object
    Dim KeyCol As Long, ValCol As Long
    
    '--- メイン表 ---
    Set ws = ActiveSheet
    LastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
    LastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
    Data = ws.Range(ws.Cells(1, 1), ws.Cells(LastRow, LastCol)).Value

    '--- 複数マスタ設定(Sheet名, Key列, Value列) ---
    '例:3マスタ結合
    MasterSheets = Array( _
        Array("Master1", 1, 2), _
        Array("Master2", 1, 2), _
        Array("Master3", 1, 2) _
    )
    
    ReDim MasterDicts(LBound(MasterSheets) To UBound(MasterSheets))

    '--- 各マスタを Dictionary に変換 ---
    For i = LBound(MasterSheets) To UBound(MasterSheets)
        Set MasterDicts(i) = CreateObject("Scripting.Dictionary")
        Call LoadMasterToDict(MasterSheets(i)(0), MasterSheets(i)(1), MasterSheets(i)(2), MasterDicts(i))
    Next i

    '--- 配列 × Dictionary で結合処理 ---
    For r = 2 To UBound(Data, 1)
        For i = LBound(MasterDicts) To UBound(MasterDicts)
            Dim keyVal As Variant
            keyVal = Data(r, 1) ' メイン表の結合キー列(例:A列)
            
            If MasterDicts(i).exists(keyVal) Then
                ' 書き込み先列は i+3 列目以降に出力(自由に変更可)
                Data(r, i + 3) = MasterDicts(i)(keyVal)
            End If
        Next i
    Next r

    '--- 一括書き戻し(高速化の肝) ---
    ws.Range(ws.Cells(1, 1), ws.Cells(LastRow, LastCol + UBound(MasterDicts) + 1)).Value = Data

    MsgBox "複数マスタ結合 完了!"

End Sub
VB

サブプロ:マスタ → Dictionary 読み込み

Sub LoadMasterToDict(SheetName As String, KeyCol As Long, ValCol As Long, dict As Object)
    Dim wsM As Worksheet
    Set wsM = Sheets(SheetName)

    Dim LastRow As Long
    LastRow = wsM.Cells(wsM.Rows.Count, KeyCol).End(xlUp).Row

    Dim arrM As Variant
    arrM = wsM.Range(wsM.Cells(2, 1), wsM.Cells(LastRow, ValCol)).Value

    Dim r As Long
    For r = 1 To UBound(arrM, 1)
        If Not dict.exists(arrM(r, 1)) Then
            dict.Add arrM(r, 1), arrM(r, ValCol)
        End If
    Next r
End Sub
VB

ポイント・特徴

  1. Dictionary でキー検索 O(1)
    • どんなにマスタ行数が多くても瞬時に検索
  2. 配列で全体処理 → 一括書き戻し
    • 数十万行でも 1 秒以内
  3. 複数マスタ対応(3〜5マスタ)
    • MasterSheets 配列に追加するだけで対応可能
  4. 自動範囲検出
    • 行・列の変化に強く、どんな表でも使える
  5. 出力列自由
    • マスタごとに好きな列に書き込める

応用例

  • マスタ数が 5 でも MasterSheets = Array(...) に追加するだけ
  • メイン表の結合キーが複数列でも対応可能(Key を組み合わせて Dictionary にすれば OK)
  • 集計や加工も配列内で自由に追加可能

実務での効果

従来 VLOOKUPこのテンプレ
20万行 × マスタ3つ → 数分20万行 × マスタ3つ → 0.5 秒前後
冗長なセル操作一括配列処理
メンテナンス困難マスタ追加も簡単

タイトルとURLをコピーしました