【问题标题】:Excel VBA: Unable to reassign value to arrayExcel VBA:无法将值重新分配给数组
【发布时间】: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 变量名
  • 我只是想概括变量名称以保护无辜的大声笑。让我煮点别的东西:)。编辑:完成。

标签: excel vba


【解决方案1】:

您正在使用

创建一些奇怪的别名
for i = 1 to 10
    Str = "str"&i
    arr(1) = "str"&i+1
    arr(2) = 0
    Dict.Add Str, arr
next

因为您在标注arr 时只创建了一个数组。

你可以创建一个字典来做你想做的事:

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

【讨论】:

  • 即使进行了更改(我不知道 Array() 函数),问题仍然存在。
  • 我用过字典字典和集合字典,但从来没有意识到制作数组字典有点棘手。我只会带一本字典。
  • stackoverflow.com/questions/2404212/… 是对同一主题的回答。
  • 字典的字典是我想我会去的。感谢您的帮助约翰
  • 您还可以查看使用 CreateObject("System.Collections.ArrayList ") 创建的数组列表字典
猜你喜欢
  • 2017-01-26
  • 1970-01-01
  • 2014-01-05
  • 2016-03-11
  • 2021-12-29
  • 1970-01-01
  • 1970-01-01
  • 2019-05-28
  • 1970-01-01
相关资源
最近更新 更多