LoginSignup
0
0

More than 3 years have passed since last update.

Dictionaryで存在しないKeyのItemを参照するとKeyが追加される(のを知らなかった・・・)

Last updated at Posted at 2020-08-03

現象

・空のDictionaryCountはもちろんゼロだし、Keysプロパティも空

    Dim dict As Dictionary
    Set dict = New Dictionary
    Debug.Print dict.Count         '0
    Debug.Print dict.Keys(0)       'インデックスが有効範囲にありません

・空のDictionaryで、追加していないKeyItemを参照すると、Keyが追加される(追記:これはばっちり明記された仕様でした)

    Dim dict As Dictionary
    Set dict = New Dictionary
    Debug.Print dict.Item("test")
    Debug.Print dict.Count         '1
    Debug.Print dict.Keys(0)       'test

・空のCollectionで同じことをするとエラーが返る

    Dim col As Collection
    Set col = New Collection
    Debug.Print col.Item("test")   'プロシージャの呼び出し、または引数が不正です

補足

・なので、こういうことはできない(.Addの前に.Removeが必要 ⇒は理解不十分でした。コメント欄参照ください)

    If IsEmpty(dict.Item("foo")) Then
        dict.Add Key:="foo", Item:=bar
    End If
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0