Django Girls and Boys 備忘録

Python、Selenium、Django、java、iPhoneアプリ、Excelマクロなどで気付いたこと、覚えておきたいことなどを載せていきます。

【ExcelVBA】Dictionaryは 「重複チェック・件数カウント・高速検索」のマクロ処理でほぼ必須の存在

Excelマクロをある程度書いてくると、
必ずこんな壁にぶつかります。

  • 行数が増えると処理が遅い

  • 重複チェックがややこしい

  • ある値が「存在するかどうか」調べたいだけなのに大変

この悩みを 一気に解決するのが Dictionary です。

実務VBAでは、Dictionaryはほぼこの3用途で使われます👇

👉 重複チェック
👉 件数カウント
👉 高速検索

この記事では、それぞれ
「どんな業務で」「どう使うのか」を
具体例つきで解説します。


まずは前提:Dictionaryとは?

Dictionaryは
「キー」と「値」をセットで保存できる高速な箱」 です。

 
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")

 

  • キー:重複不可

  • 値:何でもOK(数値・文字列・配列など)

  • Exists() で一瞬で存在判定

👉 For文で探す必要がなくなる
これが最大のメリットです。


① 重複チェック(最も使われる)

📌 実務例

  • 顧客IDの重複チェック

  • 商品コードの重複確認

  • CSV取り込み時の重複排除


❌ よくある遅い方法

 
For i = 2 To lastRow
    For j = i + 1 To lastRow
        If Cells(i, 1).Value = Cells(j, 1).Value Then
            ' 重複
        End If
    Next j
Next i

 

👉 行数が増えると地獄(O(n²))


✅ Dictionaryを使った方法例

 
Sub CheckDuplicate()

  Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    Dim i As Long
    For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row
        If dict.Exists(Cells(i, 1).Value) Then
            Cells(i, 2).Value = "重複"
        Else
            dict.Add Cells(i, 1).Value, True
        End If
    Next i

End Sub

 

ポイント

  • Exists() で一発判定

  • 比較処理が激減

  • 数万行でも高速

👉 「重複かどうか知りたい」= Dictionary


② 件数カウント(集計処理の王道)

📌 実務例

  • 商品別の販売件数

  • 担当者ごとの処理件数

  • エラーコード別の発生回数


❌ よくある回りくどい方法

  • COUNTIF を何度も書く

  • 条件ごとに For 文

👉 遅い&コードが汚くなりがち


✅ Dictionaryで一瞬集計

 
Sub CountByKey()

    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    Dim i As Long
    Dim key As String
    For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row
        key = Cells(i, 1).Value
        If dict.Exists(key) Then
            dict(key) = dict(key) + 1
        Else
            dict.Add key, 1
        End If
    Next i

    ' 結果出力
    i = 2
    For Each key In dict.Keys
        Cells(i, 3).Value = key
        Cells(i, 4).Value = dict(key)
        i = i + 1
    Next key

End Sub

 

何がすごい?

  • COUNTIF 不要

  • ピボット不要

  • 動的に集計できる

👉 VBA集計は Dictionary一択


③ 高速検索(存在チェック・対応表)

📌 実務例

  • マスタに存在するか確認

  • コード → 名称変換

  • NGリスト照合


❌ よくある非効率な方法

 
For i = 2 To masterLastRow
    If Cells(i, 1).Value = target Then
        found = True
        Exit For
    End If
Next

 

👉 毎回 For 文は非効率


✅ Dictionaryで「即答」検索

マスタを先に読み込む

 

Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
For i = 2 To masterLastRow
    dict.Add Cells(i, 1).Value, Cells(i, 2).Value
Next

 

検索側

 
If dict.Exists(targetCode) Then
    Cells(i, 3).Value = dict(targetCode)
Else
    Cells(i, 3).Value = "未登録"
End If

 

👉 検索時間はほとんどかからない


Dictionaryが「実務必須」と言われる理由

用途 Dictionary 通常処理
重複チェック Exists() 二重ループ
件数カウント 加算 COUNTIF
高速検索 一瞬 For検索

👉 処理速度・可読性・拡張性すべてで優秀


よくある注意点(初心者向け)

  • Key は重複不可(Addでエラー)

  • 上書きしたい場合は dict(key) = value

  • 数値と文字列は別キー扱いになる場合あり


まとめ:Dictionaryは「覚えたら戻れない」

実務VBAでは、Dictionaryは

👉 重複チェック
👉 件数カウント
👉 高速検索

この3つで ほぼ毎回登場します。