Excel VBA:嵌套词典问题 [英] Excel VBA: nested dictionary issue
问题描述
我无法创建嵌套字典,将其分配给变量,覆盖内部值之一,然后将其分配给另一个变量,而不会更改原始变量的值,这是我不希望的.例如,请参见以下代码:
I am not able to create a nested dictionary, assign it to a variable, overwrite one of the inner values, and then assign it to another variable without the original variable's value getting changed, which I do not want. For example, see the following code:
Option Explicit
Sub Button1_Click()
Dim d_outer As Scripting.Dictionary
Set d_outer = New Scripting.Dictionary
Dim d_inner As Scripting.Dictionary
Set d_inner = New Scripting.Dictionary
Call d_inner.Add("key", "foo")
Call d_outer.Add("first attempt", d_inner)
' Cannot use "Add", since key already exists, must use Item()
d_inner.Item("key") = "bar"
Call d_outer.Add("second attempt", d_inner)
' Print all values.
Dim v_outer As Variant
Dim v_inner As Variant
For Each v_outer In d_outer.Keys()
For Each v_inner In d_outer(v_outer).Keys()
Debug.Print "(" & v_outer & ", " & v_inner & "): '" & d_outer(v_outer)(v_inner) & "'"
Next v_inner
Next v_outer
End Sub
这将产生以下输出:
(first attempt, key): 'bar'
(second attempt, key): 'bar'
首次尝试的值应为 foo
.为什么将其更改为 bar
?我该如何解决?每当我只想更改一个值时,是否需要创建一个新的字典,该字典是d_inner的精确副本?如果是这样,有没有简便的方法?
The first attempt's value should be foo
. Why is it getting changed to bar
? How do I fix this? Do I need to create a new dictionary that's an exact copy of d_inner every time I want to change only one of the values? If so, is there an easy way to do that?
推荐答案
在第一个集合中,您创建了对对象的引用,而不是在其中放置值.因此,当您更改内部集合时,它会在初始外部集合中更新.
In your first collection you have created a reference to an object rather than placing a value in there (for example). So as you change the inner collection it is updated in the initial outer collection.
您需要创建一个 New
对象以放入第二个集合中.像这样:
You need to create a New
object to put into the second collection. Like this:
' Cannot use "Add", since key already exists, must use Item()
Set d_inner = New Scripting.Dictionary
Call d_inner.Add("key", "bar")
赠予:
(first attempt, key): 'foo'
(second attempt, key): 'bar'
根据您要在此处实现的目标,您可能会发现类在执行此类任务时更加灵活
Depending on what you are trying to achieve here, you might find that classes are more flexible with these kinds of tasks
这篇关于Excel VBA:嵌套词典问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!