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")
Run Code Online (Sandbox Code Playgroud)
如何使用密钥修改内部集合的值?
Alex K.关于使用a的建议Dictionary是正确的,但我认为这里的问题比他的回答更为通用.一个Collection(为此事或索引位置)密钥仅读好,不写.
所以在这一行:
dFeat("M1")("TOTAL") = 88 ' Error here
Run Code Online (Sandbox Code Playgroud)
dFeat("M1")很好.它返回Collection您添加的键"M1".发生错误是因为您尝试直接分配给该集合的元素.一般来说,如果c是a Collection,c("TOTAL")(或c(2))不能是左值.
正如Alek K.所说,解决这个问题的最佳方法是使用a Dictionary作为内部"集合",或者使用内部和外部.以下是如何使用内部看起来:
Dim d As Dictionary
Set d = New Dictionary
d("PASSED") = 3
d("TOTAL") = 4
dFeat.Add d, "M1"
Run Code Online (Sandbox Code Playgroud)
然后这行:
dFeat("M1")("TOTAL") = 88
Run Code Online (Sandbox Code Playgroud)
将dFeat("M1")("TOTAL") 是有效的,因为是一个有效的左值.
如果由于某种原因您不能或不想包含MS Scripting Runtime,则必须使用以下内容替换失败的行:
Dim c As Collection
Set c = dFeat("M1")
Call c.Remove("TOTAL")
Call c.Add(88, "TOTAL")
Run Code Online (Sandbox Code Playgroud)
或者更简洁:
Call dFeat("M1").Remove("TOTAL")
Call dFeat("M1").Add(88, "TOTAL")
Run Code Online (Sandbox Code Playgroud)
然后,您可以读取值dFeat("M1")("TOTAL"),但仍然无法分配给它.
| 归档时间: |
|
| 查看次数: |
19435 次 |
| 最近记录: |