Dictionary高速テンプレ(JOIN活用)
大量データを扱うとき、Dictionary と Join関数 を組み合わせると「ユニーク化+高速結合」が一気にできます。初心者でも理解しやすいように、コード例やテンプレートをかみ砕いて説明します。
基本の考え方
- Dictionaryでユニーク化
→ キーは重複不可なので、同じ値が自動的に排除される。 - Keysで一覧取得
→ ユニーク化されたキーを配列として取り出せる。 - Joinで文字列化
→ 配列を一気に結合して文字列にできる。
テンプレ1:配列をユニーク化して結合
Sub DictJoin_Unique()
Dim fruits As Variant
fruits = Array("りんご", "みかん", "バナナ", "りんご", "ぶどう")
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
Dim f As Variant
For Each f In fruits
dict(f) = True ' キーだけ利用
Next f
' ユニーク化されたキーを配列に
Dim arr As Variant: arr = dict.Keys
' Joinで結合
Dim result As String
result = Join(arr, ", ")
MsgBox "ユニークリスト=" & result
End Sub
VB- 結果:
ユニークリスト=りんご, みかん, バナナ, ぶどう
テンプレ2:シートの列をユニーク化して結合
Sub DictJoin_FromSheet()
Dim ws As Worksheet: Set ws = Worksheets("Data")
Dim lastRow As Long: lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
Dim rg As Range: Set rg = ws.Range("A2:A" & lastRow)
Dim v As Variant: v = rg.Value
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
Dim r As Long
For r = 1 To UBound(v, 1)
dict(Trim(v(r, 1))) = True
Next r
Dim arr As Variant: arr = dict.Keys
Dim result As String: result = Join(arr, " / ")
MsgBox "ユニーク顧客コード=" & result
End Sub
VB- ポイント:
- A列の顧客コードをユニーク化。
/区切りで結合。
テンプレ3:カテゴリ別にJOIN(2段Dictionary)
Sub DictJoin_ByCategory()
Dim ws As Worksheet: Set ws = Worksheets("Data")
Dim rg As Range: Set rg = ws.Range("A2:B20") ' A=カテゴリ, B=商品
Dim v As Variant: v = rg.Value
Dim dictOuter As Object: Set dictOuter = CreateObject("Scripting.Dictionary")
Dim dictInner As Object
Dim r As Long, cat As String, prod As String
For r = 1 To UBound(v, 1)
cat = v(r, 1)
prod = v(r, 2)
If dictOuter.Exists(cat) Then
Set dictInner = dictOuter(cat)
Else
Set dictInner = CreateObject("Scripting.Dictionary")
dictOuter(cat) = dictInner
End If
dictInner(prod) = True
Next r
' 出力
Dim k As Variant
For Each k In dictOuter.Keys
MsgBox "カテゴリ=" & k & vbCrLf & "商品=" & Join(dictOuter(k).Keys, ", ")
Next k
End Sub
VB- ポイント:
- カテゴリごとに商品をユニーク化。
- JOINで一覧表示。
テンプレ4:JOINでログ出力(改行区切り)
Sub DictJoin_Log()
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
dict("Step1") = "開始"
dict("Step2") = "データ読み込み"
dict("Step3") = "集計完了"
Dim arr As Variant: arr = dict.Items
Dim result As String: result = Join(arr, vbCrLf)
MsgBox result
End Sub
VB- 結果:
開始 データ読み込み 集計完了
例題で練習
'例1:配列をユニーク化して結合
Sub Example1()
DictJoin_Unique
End Sub
'例2:シートの列をユニーク化して結合
Sub Example2()
DictJoin_FromSheet
End Sub
'例3:カテゴリ別にJOIN
Sub Example3()
DictJoin_ByCategory
End Sub
'例4:JOINでログ出力
Sub Example4()
DictJoin_Log
End Sub
VB初心者向けポイント
- Dictionaryでユニーク化 → 重複を自動排除。
- Keysで配列化 → Joinで結合 → 一気に文字列化できる。
- 区切り文字を工夫 →
", "や" / "やvbCrLf。 - 2段Dictionaryでカテゴリ別JOIN → グループごとの一覧作成に便利。
- 実務で便利 → 顧客コード一覧、商品リスト、ログ出力など。
👉 この「Dictionary高速テンプレ(JOIN)」を覚えておけば、Excel VBAで ユニーク化+文字列結合+グループ化 を高速に処理できるようになります。
