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?
You cannot update a value type in a collection;
Add a reference to the Microsoft Scripting runtime, replace
Collection
withDictionary
& it should work.Alex K.'s advice about using a
Dictionary
is correct, but I think the issue here is more general than his answer lets on. ACollection
key (or index position for that matter) is only good for reading, not writing.So in this line:
dFeat("M1")
is fine. It returns theCollection
you added with key "M1". The error is happening because you try to directly assign to an element of that collection. In general, ifc
is aCollection
,c("TOTAL")
(orc(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:Then the line:
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:
or more concisely:
Then, you can read the value of
dFeat("M1")("TOTAL")
, but you still can't assign to it.