更改 VBA 字典中的数组值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2404212/
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
Changing array values in a VBA dictionary
提问by Michael D. Irizarry
I have a piece of code that does not seem to do what it is expected to do. VBA Arrays are mutable by all means, but it seems that when they are stored into a Dictionary as values of some keys, they are not mutable anymore. Any ideas?
我有一段代码似乎没有做预期的事情。VBA 数组无论如何都是可变的,但似乎当它们作为某些键的值存储到字典中时,它们就不再可变了。有任何想法吗?
Sub foo()
Dim mydict As New Dictionary
mydict.Add "A", Array(1, 2, 3)
MsgBox mydict("A")(1)
''# The above shows 2, which is fine
mydict("A")(1) = 34
MsgBox mydict("A")(1)
''# The above also shows 2, which is not fine
End Sub
回答by Michael D. Irizarry
It seems you'll need yet to set another var to update the array value.
看来您还需要设置另一个 var 来更新数组值。
mArray = mydict.Item(1)
mArray(1) = 34
mydict.Item(1) = mArray
回答by Sepehr Moravej
I would have written this answer as a comment to Mr. Irizarry's answer, but I'm not allowed. Anyway.... I tried writing that last line of code (below) to assign the array to the first item of the dictionary, but it didn't work. The array in that item remained as it was before.
我会写这个答案作为对 Irizarry 先生答案的评论,但我不被允许。无论如何......我尝试编写最后一行代码(如下)将数组分配给字典的第一项,但它没有用。该项目中的数组保持原样。
mydict.items(1) = mArray
Based on what I read elsewhere, it seems to have to do with the instance of the dictionary you're calling upon. I changed it to the following line and it worked.
根据我在别处读到的内容,这似乎与您正在调用的字典实例有关。我将其更改为以下行并且它起作用了。
mydict(mydict.keys(1)) = mArray
I'm still not sure why that is the case, but there it is.
我仍然不确定为什么会这样,但确实如此。
回答by ádám Bukovinszki
I created a Procedure to solve the same issue, so I could keep it as a "oneliner":
我创建了一个程序来解决相同的问题,因此我可以将其保留为“oneliner”:
Private Sub pReplaceDicArray(Dic As Object, kEy As Variant, Element As Integer, NewValue)
Dim tempArray As Variant
tempArray = Dic(kEy)
tempArray(Element) = NewValue
Dic(kEy) = tempArray
End Sub
' call as:
' Call mReplaceDicArray(Dic, "A", 1, 8)