YUKIBEのBLOG

日常のメモ書き

VBA:辞書

参考

【Excel VBA入門】Dictionaryとは?データ管理が楽になる連想配列の作り方 – Valmore
【エクセルVBA】Dictionaryに格納したキーと要素をリストに書き出す方法
【VBA入門】Dictionaryオブジェクト(連想配列)の使い方 | 侍エンジニアブログ
Dictionary オブジェクト | Microsoft Docs

MSリファレンス

Dictionary オブジェクト>

Dim d                   'Create a variable
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"     'Add some keys and items
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...
メソッド 説明
Add Dictionary オブジェクトに新しいキー/アイテムのペアを追加します。
Exists 指定したキーが Dictionary オブジェクト内に存在するかどうかを示すブール値を返します。
Items Dictionary オブジェクト内のすべてのアイテムの配列を返します。
Keys Dictionary オブジェクト内のすべてのキーの配列を返します。
Remove Dictionary オブジェクトから、指定したキー/アイテムのいずれかのペアを削除します。
RemoveAll Dictionary オブジェクト内のすべてのキー/アイテムのペアを削除します。
プロパティ 説明
CompareMode Dictionary オブジェクト内でキーを比較するために比較モードを設定するか返します。
Count Dictionary オブジェクト内のキー/アイテムのペアの数を返します。
Item Dictionary オブジェクト内のアイテムの値を設定するか返します。
Key Dictionary オブジェクト内の既存のキー値に対して新しいキー値を設定します。

サンプル

Public Sub aTEST_Dictionary()

  '===========================================================
  '【事前バインディング】
  '   Microsoft Scripting Runtime
  '    Dim dicUser As Dictionary
  '    Set dicUser = New Dictionary
  '===========================================================
  '【遅延バインディング】
  '  Dim Dictionary名 As Object
  '  Set Dictionary名 = CreateObject("Scripting.Dictionary")
  '===========================================================


  '=====================================================
  '// 追加・削除・取得・カウント・KEY存在確認
  '=====================================================
  Dim dic01 As Dictionary
  Set dic01 = New Dictionary
  
'// 追加
  dic01.Add "KEY", "VAL"    'HDR
  dic01.Add "a", "AAAA"     'Add some keys and items
  dic01.Add "b", "BBBB"
  dic01.Add "c", "CCCC"
  
'// カウント
  Debug.Print dic01.Count          '// カウント
  
'// 取得
  Debug.Print dic01.Item("b")    '// KeyのValue
  
  Debug.Print dic01.Keys(0)    '// HDR Value
  Debug.Print dic01.Items(0)
  Debug.Print dic01.Item(dic01.Keys(0))    '// HDR Value
        
  Dim vFE_Key As Variant
  For Each vFE_Key In dic01
      Debug.Print vFE_Key, dic01(vFE_Key)
  Next vFE_Key
        
'// IsExists
  If Not dic01.Exists("d") Then dic01.Add "d", "DDDD"
  If Not dic01.Exists("d") Then dic01.Add "d", "DDDD"
  
  Debug.Print "キー名一覧: " & Join(dic01.Keys, " | ")
  Debug.Print "値一覧    : " & Join(dic01.Items, " | ")
  
'//
  dic01.Remove "b"
  Debug.Print "キー名一覧: " & Join(dic01.Keys, " | ")
  Debug.Print "値一覧    : " & Join(dic01.Items, " | ")

'//
  dic01.RemoveAll
  Debug.Print "キー名一覧: " & Join(dic01.Keys, " | ")
  Debug.Print "値一覧    : " & Join(dic01.Items, " | ")
  
End Sub