Excel VBA : Unable to reassign value to array

标签 excel vba

我有循环遍历字典的代码。字典中每个键的值是一个包含 2 项的数组(字典看起来像 name: [string, integer])。 当我稍后引用字典时,我可以看到并打印属于字典条目的数组中的字符串和整数,但我无法通过像dictionary(name)(2) = 5;这样的正常赋值来更改整数。在代码中执行此操作后,我将数组值打印到调试文件,并且数组值是原始值,而不是其更改后的值。我不知道为什么这不起作用,以及如何让它起作用。我在数组上读到的所有内容都说你只需分配 array(0) = some 。

下面是部分代码:

定义原始字典:

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 尺寸时仅创建了一个数组。

您可以创建一个字典的字典来执行您想要的操作:

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

关于Excel VBA : Unable to reassign value to array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36698523/

相关文章:

vba - 删除特定列中具有特定值的行

excel - 在excel中仅验证字符串值的公式

windows - Excel报表框架

Excel VBA - 在多列上排序后取消选择范围

vba - 如何使用来自另一个工作簿上的单元格引用的自动筛选条件

vba - 确定带有日期的单元格是否包含特定年份

excel - 动态创建命名单元格

vba - 如何使用 VBA 在 Excel 中更改图表的范围?

ms-access - 为什么我不能直接使用 CurrentDB() 方法用 vba 重新链接表?

excel - 错误处理在Error.Number 3021上无法按预期工作