Dim dFeat As Collection
Set dFeat = New Collection
Dim cObj As Collection
Set cObj = New Collection
cObj.Add 3, "PASSED"
cObj.Add 4, "TOTAL"
dFeat.Add cObj, "M1"
Set cObj = New Collection
cObj.Add 5, "PASSED"
cObj.Add 6, "TOTAL"
dFeat.Add cObj, "M2"
dFeat("M1")("TOTAL") = 88 ' Error here
Debug.Print dFeat("M1")("TOTAL")
How do I modify the value of inner collection using the key?
Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value.
Assign a new value to an existing key to change the valueUse the format dict[key] = value to assign a new value to an existing key.
hashmap. put(key, hashmap. get(key) + 1); The method put will replace the value of an existing key and will create it if doesn't exist.
You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.
Alex K.'s advice about using a Dictionary
is correct, but I think the issue here is more general than his answer lets on. A Collection
key (or index position for that matter) is only good for reading, not writing.
So in this line:
dFeat("M1")("TOTAL") = 88 ' Error here
dFeat("M1")
is fine. It returns the Collection
you added with key "M1". The error is happening because you try to directly assign to an element of that collection. In general, if c
is a Collection
, c("TOTAL")
(or c(2)
) can't be an lvalue.
As Alek K. says, the best way around this is to use a Dictionary
for the inner "collections", or for both the inner and outer. Here is how using one for the inner would look:
Dim d As Dictionary
Set d = New Dictionary
d("PASSED") = 3
d("TOTAL") = 4
dFeat.Add d, "M1"
Then the line:
dFeat("M1")("TOTAL") = 88
will work because dFeat("M1")("TOTAL")
is a valid lvalue.
If for some reason you can't or don't want to include the MS Scripting Runtime, you'll have to replace the failing line with something like:
Dim c As Collection
Set c = dFeat("M1")
Call c.Remove("TOTAL")
Call c.Add(88, "TOTAL")
or more concisely:
Call dFeat("M1").Remove("TOTAL")
Call dFeat("M1").Add(88, "TOTAL")
Then, you can read the value of dFeat("M1")("TOTAL")
, but you still can't assign to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With