vba 按键修改值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5709444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Modify value by key
提问by Pablo
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?
如何使用键修改内部集合的值?
采纳答案by jtolle
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.
Alex K. 关于使用 a 的建议Dictionary
是正确的,但我认为这里的问题比他的回答更笼统。一Collection
键(或为此事索引位置)仅用于阅读,不写好。
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 thatcollection. In general, if c
is a Collection
, c("TOTAL")
(or c(2)
) can't be an lvalue.
dFeat("M1")
很好。它返回Collection
您添加的键“M1”。发生错误是因为您尝试直接分配给该集合的元素。一般来说, ifc
是 a Collection
,c("TOTAL")
(或c(2)
)不能是左值。
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:
正如 Alek K. 所说,解决此问题的最佳方法是将 aDictionary
用于内部“集合”,或者同时用于内部和外部。以下是将一个用于内部的外观:
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")
isa valid lvalue.
会起作用,因为它dFeat("M1")("TOTAL")
是一个有效的左值。
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:
如果由于某种原因您不能或不想包含 MS Scripting Runtime,则必须用以下内容替换失败的行:
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 readthe value of dFeat("M1")("TOTAL")
, but you still can't assign to it.
然后,您可以读取的值dFeat("M1")("TOTAL")
,但您仍然无法分配给它。
回答by Alex K.
You cannot update a value type in a collection;
您不能更新集合中的值类型;
Dim c as new Collection
c.add 42, "wth"
c("wth") = 88 //will error also
Add a reference to the Microsoft Scripting runtime, replace Collection
with Dictionary
& it should work.
添加对 Microsoft 脚本运行时的引用,替换Collection
为Dictionary
& 它应该可以工作。