Dictionary の Add・Remove
Excel VBAで Dictionary を使うときに必ず覚えておきたいのが、
キーと値を追加する Add と 削除する Remove です。
初心者向けに、コード例やテンプレートをかみ砕いて説明します。
基本の考え方
- Addメソッド
dict.Add Key, Item
→ 新しいキーと値を追加。キーは重複不可。 - Removeメソッド
dict.Remove Key
→ 指定したキーを削除。存在しないキーを指定するとエラー。 - RemoveAllメソッド
dict.RemoveAll
→ 全てのキーと値を削除。
テンプレ1:Addでキーと値を追加
Sub Dict_AddExample()
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
' データ追加
dict.Add "A001", "りんご"
dict.Add "A002", "みかん"
dict.Add "A003", "バナナ"
' 出力
Dim k As Variant
For Each k In dict.Keys
Debug.Print k, dict(k)
Next k
End Sub
VB- 結果:
A001 りんご A002 みかん A003 バナナ
テンプレ2:Removeでキーを削除
Sub Dict_RemoveExample()
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
dict.Add "A001", "りんご"
dict.Add "A002", "みかん"
dict.Add "A003", "バナナ"
' A002を削除
dict.Remove "A002"
' 出力
Dim k As Variant
For Each k In dict.Keys
Debug.Print k, dict(k)
Next k
End Sub
VB- 結果:
A001 りんご A003 バナナ
テンプレ3:RemoveAllで全削除
Sub Dict_RemoveAllExample()
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
dict.Add "A001", "りんご"
dict.Add "A002", "みかん"
' 全削除
dict.RemoveAll
MsgBox "要素数=" & dict.Count ' → 0
End Sub
VB- ポイント: 全てのキーと値を一気に消せる。
テンプレ4:Add時に重複チェック(Exists)
Sub Dict_AddSafe()
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
Dim key As String: key = "A001"
Dim value As String: value = "りんご"
If Not dict.Exists(key) Then
dict.Add key, value
Else
MsgBox "キー " & key & " は既に存在します"
End If
End Sub
VB- ポイント:
Addは同じキーを追加するとエラーになる。Existsで事前チェックすると安全。
例題で練習
'例1:Addでキーと値を追加
Sub Example1()
Dict_AddExample
End Sub
'例2:Removeでキーを削除
Sub Example2()
Dict_RemoveExample
End Sub
'例3:RemoveAllで全削除
Sub Example3()
Dict_RemoveAllExample
End Sub
'例4:Add時に重複チェック
Sub Example4()
Dict_AddSafe
End Sub
VB初心者向けポイント
- Addは重複不可: 同じキーを追加するとエラーになる。
- Removeは存在しないキーでエラー:
Existsで確認してから削除。 - RemoveAllで全削除: 初期化したいときに便利。
- 安全に使う:
Existsを組み合わせると安心。
👉 この「Add・Removeテンプレ」を覚えておけば、Dictionaryを使った データ追加・削除・初期化 を安全に実務へ応用できます。
