VBA Dictionary コードで確認

基本パターン

Dictionaryオブジェクト宣言、データ追加、データ取得

Sub SampleDictionaryBasic()
    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    
    ' データの追加
    dict.Add "apple", "りんご"
    dict.Add "banana", "バナナ"
    dict.Add "orange", "オレンジ"
    
    ' データの取得
    Debug.Print "apple の意味は " & dict("apple")
    
    ' 全件表示(For Each)
    Dim key As Variant
    For Each key In dict.Keys
        Debug.Print key & "" & dict(key)
    Next key
End Sub

existメソッド

※ キーの重複は許されないでの、基本的にAddを利用する前には「exist」メソッドで存在確認

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

    Dim productIds As Variant
    productIds = Array("A001", "A002", "A001", "A003", "A002")

    Dim pid As Variant

    ' 重複を除外してDictionaryに登録
    For Each pid In productIds
        If Not dict.Exists(pid) Then
            dict.Add pid, "商品:" & pid
        End If
    Next pid

    ' 重複が排除されていることを確認
    Dim key As Variant
    Debug.Print "◆ 登録結果(重複排除済み)"
    For Each key In dict.Keys
        Debug.Print key & "" & dict(key)
    Next key
    
    Debug.Print "登録数:" & dict.Count
End Sub

リストの値に配列

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

    Dim scores() As Variant
    scores = Array(90, 85, 88)

    dict.Add "kazu", scores

    Dim i As Long
    For i = LBound(dict("kazu")) To UBound(dict("kazu"))
        Debug.Print "kazuの点数 " & i + 1 & "回目: " & dict("kazu")(i)
    Next i
End Sub

リストの値にリスト

シンプル版(理解用)

Sub SampleNestedDictionary1()
    Dim dictAll As Object, dictInner As Object
    Set dictAll = CreateObject("Scripting.Dictionary")

    ' 内側のDictionary
    Set dictInner = CreateObject("Scripting.Dictionary")
    dictInner.Add "数学", 90
    dictInner.Add "英語", 85

    ' 外側のDictionaryに内側を格納
    dictAll.Add "kazu", dictInner
    
    ' 取り出し
    Debug.Print "数学の点数: " & dictAll("kazu")("数学")
End Sub

通常版

Sub SampleNestedDictionary2()
    Dim dictAll As Object, dictInner As Object
    Set dictAll = CreateObject("Scripting.Dictionary")

    ' --- kazuのデータ ---
    Set dictInner = CreateObject("Scripting.Dictionary")
    dictInner.Add "数学", 90
    dictInner.Add "英語", 85
    dictAll.Add "kazu", dictInner

    ' --- tomのデータ ---
    Set dictInner = CreateObject("Scripting.Dictionary")
    dictInner.Add "数学", 75
    dictInner.Add "英語", 92
    dictAll.Add "tom", dictInner

    ' --- データ一覧表示 ---
    Dim name As Variant, subject As Variant
    For Each name In dictAll.Keys
        Debug.Print "" & name
        
        For Each subject In dictAll(name).Keys
            Debug.Print "  " & subject & ": " & dictAll(name)(subject)
        Next subject

        Debug.Print "---------------------"
    Next name
End Sub

コメント