更新存储在VBA字典中的数组

时间:2014-02-21 16:42:18

标签: arrays excel vba data-structures dictionary

我正在创建一个使用嵌套字典和最低级别列表的数据结构。以下是我的数据示例:

Country, Customer, Purchased
US, Alan, Lawnmower
US, Alan, Hammer
US, Karen, Donkey
US, Simon, Mustang
MX, Carl, Lawnmower
MX, Alan, Donkey
...

我想到的数据结构看起来像dictionary --> dictionary --> array - 即country --> customer --> purchased。计划是每个dictionary --> dictionary组合有一个新数组。

但是,当我尝试更新数组时,它似乎链接到dictionary --> dictionary结构的所有较低级别。也就是说,在处理完第三行之后,出现以下情况:

US --> Alan --> [Lawnmower, Hammer, Donkey]
US --> Karen --> [Lawnmower, Hammer, Donkey]

......而我期待看到的是:

US --> Alan --> [Lawnmower, Hammer]
US --> Karen --> [Donkey]

这是我试图使用的代码:

i_p = UBound(purchased_array)

Redim Preserve purchased_array(i_p + 1)

purchased_array(i+p + 1) = item ' new item to add to the array

dataset(country)(customer) = purchased_array

但是,这会导致dictionary --> dictionary结构的每个最低级别引用基本相同的数组。

对我做错了什么的想法?

2 个答案:

答案 0 :(得分:5)

如果字典中有数组,则必须先将其从字典中删除,然后才能对其进行修改。然后把它放回去。

Sub Tester()

Dim x As Long, y As Long
Dim dict As New Scripting.Dictionary
Dim d As Scripting.Dictionary
Dim arr

    For x = 1 To 3
        Set d = New Scripting.Dictionary
        For y = 1 To 3
            d.Add "nextkey" & y, Array("A_" & x & "_" & y, _
                                       "B_" & x & "_" & y)
        Next y
        dict.Add "key" & x, d
    Next x

    Debug.Print Join(dict("key1")("nextkey1"), ", ") '>> A_1_1, B_1_1

    'try to modify array while stored in dictionary...
    dict("key1")("nextkey1")(1) = "newValue1" '<<< doesn't work!

    Debug.Print Join(dict("key1")("nextkey1"), ", ") '>> A_1_1, B_1_1

    'have to pull it out of the dictionary if you want to change it...
    arr = dict("key1")("nextkey1")
    arr(1) = "newValue2"
    dict("key1")("nextkey1") = arr

    Debug.Print Join(dict("key1")("nextkey1"), ", ") '>> A_1_1, newValue2

End Sub

答案 1 :(得分:0)

字典包含多组对。此外,Dictionary中的键列表必须是唯一的。在包含Country&amp ;;之间关系的顶级词典中客户,无论是国家还是客户都不是该标准所独有的。所以,我认为字典不合适。也许你可以试试Dictionary -> Array -> Array