Reputation: 99
In Python I am used to having something like a defaultdict where I can just append many values to a given key. In Excel it seems like if I use the Dictionary object from the Scripting Runtime, I can only add one item per key.
Is there a way I can do something like this:
I hope I am being clear enough. Maybe instead of a list I mean an array, not sure.
Attempt:
Dim collect As New collection
If Not dict.Exists(key) Then
dict.Add key, collect
End If
collect = dict.Item(key)
collect.Add (val)
dict.Item(key) = collect
Upvotes: 1
Views: 2293
Reputation: 56745
You are missing the Set
keyword required in VBA to assign to objects. However you can get around them with a much more compact format anyway:
If Not dict.Exists(Key) Then dict.Add Key, New Collection
dict.Item(Key).Add Val
If you want to keep your old format, then this is how:
Dim collect As New collection
If Not dict.Exists(key) Then
dict.Add key, collect
End If
Set collect = dict.Item(key)
collect.Add (val)
Set dict.Item(key) = collect
But the more compact format above works fine as well.
Upvotes: 1