Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify value by key

Tags:

vba

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?

like image 290
Pablo Avatar asked Apr 18 '11 22:04

Pablo


People also ask

How do I change my key value?

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.

How do I change the value of a key in python?

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.

How do I change the value of a key in a HashMap?

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.

How do you take the value of a key?

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.


1 Answers

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.

like image 131
jtolle Avatar answered Oct 11 '22 15:10

jtolle