VBA Dictionaryのサンプル(Map)

VBAのDictionaryのサンプルです。Excel、Accessとも同じです。

目次

サンプル Dictionary
  キーと値をすべて取得する(for文)
  件数を取得する(Count)
  指定のキーがあるか真偽値を返す(Exists)
  キーを指定して値を変更する
  キーを指定して削除する(Remove)

Dictionary

Dictionaryのサンプルです。

追加:ディクショナリ.Add キー,値
参照:ディクショナリ(キー)
Sub test1()

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

    color.Add "a", "赤"
    color.Add "b", "黄"
    color.Add "c", "青"
    
    Debug.Print color("a") '赤
    Debug.Print color("b") '黄
    Debug.Print color("c") '青

End Sub

6~8行目は、dictionaryにキーと値を追加しています。
10~12行目は、キーを指定して値を表示しています。

キーと値をすべて取得する(for文)

For Each文:For Each キー In ディクショナリ
For文:For i = 0 To ディクショナリ.Count - 1
全てのキーを取得:変数 = ディクショナリ.keys
全ての値を取得:変数 = ディクショナリ.items

keysメソッドは、Dictionaryのすべてのキーの配列を返します。
Itemsメソッドは、Dictionaryのすべての値の配列を返します。

Sub test1()
    Dim color As Object
    Set color = CreateObject("Scripting.Dictionary")

    color.Add "a", "赤"
    color.Add "b", "黄"
    color.Add "c", "青"

    Dim c1 As Variant
    
    For Each c1 In color
        Debug.Print c1 'a b c (キー)
        Debug.Print color(c1) '赤 黄 青 (値)
    Next

    Dim i As Integer
    Dim key As Variant
    Dim item As Variant
    
    key = color.keys 'keysメソッド
    item = color.items 'Itemsメソッド
    
    For i = 0 To color.Count - 1
        Debug.Print key(i) & "です" 'aです bです cです
        Debug.Print item(i) & "です" '赤です 黄です 青です
    Next
End Sub

11行目は、For Each文でループさせています。
変数のc1は、キーになります。
23行目は、for文で件数分ループさせています。
20,21行目のように予めキーと値を取得しておきます。

件数を取得する(Count)

ディクショナリ.Count
Sub test1()

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

    color.Add "a", "赤"
    color.Add "b", "黄"
    color.Add "c", "青"

    Debug.Print color.Count '3

End Sub

10行目は、countでdictionaryの要素の件数を取得しています。

指定のキーがあるか真偽値を返す(Exists)

ディクショナリ.Exists(キー)
Sub test1()

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

    color.Add "a", "赤"
    color.Add "b", "黄"
    color.Add "c", "青"

    If color.Exists("b") = True Then
        Debug.Print "存在します"
    End If

End Sub

10行目は、Dictionaryに指定のキーが存在するか確認しています。

キーを指定して値を変更する

ディクショナリ(キー) = 値
ディクショナリ.item(キー) = 値
Sub test1()

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

    color.Add "a", "赤"
    color.Add "b", "黄"
    color.Add "c", "青"

    color("b") = "オレンジ"
    Debug.Print color("b") 'オレンジ

    color.item("c") = "緑"
    Debug.Print color("c") '緑
End Sub

10,13行目は、キーを指定して値を変更しています。

キーを指定して削除する(Remove)

ディクショナリ.Remove(キー)
Sub test1()

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

    color.Add "a", "赤"
    color.Add "b", "黄"
    color.Add "c", "青"

    color.Remove ("b")

    For Each c1 In color
        Debug.Print c1 & color(c1) 'a赤 c青
    Next

End Sub

10行目は、Removeでキーを指定して削除しています。

関連の記事

VBA 文字列を切り出す(Left/Mid/Right)
Excel VBA 文字列を切り出す(Left/Mid/Right)

△上に戻る