分かりやすく、使いやすく。

Dictionary の要素数をカウントする方法

スポンサーリンク

Dictionary オブジェクトの要素数を取得するには、 Countプロパティを使用します。

Dictionary の要素数を取得

サンプルコードは次の通りです。

VBA(実行可能なサンプルコード)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Option Explicit
 
Sub test1()
    'Dictionary の初期化
    Dim dicColors As Object
    Set dicColors = CreateObject("Scripting.Dictionary")
    
    Debug.Print "要素数=" & dicColors.Count
    
    'キーと値を追加。
    dicColors.Add "red", "赤"
    dicColors.Add "blue", "青"
    dicColors.Add "pink", "桃"
    
    Debug.Print "要素数=" & dicColors.Count
    
    dicColors.Add "green", "緑"
    
    Debug.Print "要素数=" & dicColors.Count
End Sub 

上記の実行結果は次の通りです。

実行結果
1
2
3
要素数=0
要素数=3
要素数=4 

Dictionary の要素数だけループする

Dictionary オブジェクトの Count で取得した数だけループするサンプルコードは次の通りです。

VBA(実行可能なサンプルコード)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Option Explicit
 
Sub test2()
    'Dictionary の初期化
    Dim dicColors As Object
    Set dicColors = CreateObject("Scripting.Dictionary")
    
    'キーと値を追加。
    dicColors.Add "red", "赤"
    dicColors.Add "blue", "青"
    dicColors.Add "pink", "桃"
    
    'ループ用の変数
    Dim i As Integer
    Dim keys
    Dim items
    
    keys = dicColors.keys
    items = dicColors.items
    
    'ディクショナリの要素数だけループする
    For i = 0 To dicColors.Count - 1
        Debug.Print "キーの値:" & keys(i) & "、格納している値:" & items(i)
    Next i
End Sub 

上記の実行結果は次の通りです。

実行結果
1
2
3
キーの値:red、格納している値:赤
キーの値:blue、格納している値:青
キーの値:pink、格納している値:桃 
スポンサーリンク
スポンサーリンク