Excel VBA:无法重新分配数组值

我有通过字典循环的代码。 字典中每个键的值是一个2项数组(字典看起来像名称:[string,整数])。 当我在后面引用字典时,可以看到并打印属于字典条目的数组中的string和整数,但是我不能通过像字典(name)(2)= 5这样的正常赋值来更改整数。 在代码中这样做之后,我将数组值打印到一个debugging文件,并且数组值是原始值,而不是其更改的值。 我不知道为什么这不起作用,我怎么才能使它工作。 我在数组上读到的所有东西都表示你只需要赋值array(0)= something。

这里是以下代码的一部分:

定义原始字典:

dim Dict as Object Set Dict = CreateObject("Scripting.Dictionary") for i = 1 to 10 strnum = "str"&i Dict.Add strnum, array("str"&i+1,0) next 'printing each item in dict returns "Str1: [str2,0]", etc. as it should 

与字典一起工作:

 For each Cell in Range("a1:a11") If Cell.Value <> "" And Dict.exists(Cell.Value) Then name = Cell.Value range = Dict(name)(0) If Dict(name)(1) = 1 Then 'we have already located the name here Else Dict(name)(1) = 1 s = "Setting the found flag to " & Dict(name)(1) debug.print s 'Dict(name)(1) returns 0 when it should return 1 end if end if next cell 

范围a1:a11是Str1,Str2,Str3,Str4,Str5 … Str11。

我能做些什么来解决这个问题?

你正在创造一些奇怪的别名

 for i = 1 to 10 Str = "str"&i arr(1) = "str"&i+1 arr(2) = 0 Dict.Add Str, arr next 

因为您只在尺寸为arr时创build了单个数组。

你可以创build一个字典字典来做你想要的:

 Sub test() Dim Dict As Object, Str, i, arr Set Dict = CreateObject("Scripting.Dictionary") For i = 1 To 10 Set arr = CreateObject("Scripting.Dictionary") arr.Add 1, "str" & i + 1 arr.Add 2, 0 Str = "str" & i Dict.Add Str, arr Next For i = 1 To 10 Debug.Print (Dict("str" & i)(1)) Next i Dict("str1")(1) = "Bob" Debug.Print Dict("str1")(1) 'prints Bob End Sub