【发布时间】:2016-04-18 15:38:22
【问题描述】:
我有遍历字典的代码。字典中每个键的值是一个 2 项数组(字典看起来像名称:[字符串,整数])。 当我稍后引用字典时,我可以看到并打印属于字典条目的数组中的字符串和整数,但我不能通过像 dictionary(name)(2) = 5; 这样的普通赋值来更改整数;在代码中这样做之后,我将数组值打印到调试文件中,数组值是原始值,而不是更改后的值。我不知道为什么这不起作用,以及如何使它起作用。我在数组上读到的所有内容都说您只需分配 array(0) = 一些东西。
下面是部分代码:
定义原始字典:
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。
我能做些什么来解决这个问题?
【问题讨论】:
-
代码 sn-p 有很多错误。 (例如 -- 在
CreateObject之前没有Set并在循环中使用Add会导致key already associated with value错误)。请发布实际工作并可靠地重现问题的代码。 -
更新了代码。它现在应该可以正常工作(或不工作)。
-
但
String不是有效的 VBA 变量名 -
我只是想概括变量名称以保护无辜的大声笑。让我煮点别的东西:)。编辑:完成。