本文介绍了更新存储在VBA字典的阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建使用嵌套词典和在最低级别的列表的数据结构。这里是我的数据的样本:

I'm creating a data structure that uses nested dictionaries and a list at the lowest level. Here's a sample of my data:

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

数据结构我想到看起来像词典 - >字典 - >阵列 - 即国家 - >客户 - >购买。该计划是在那里每新阵列的字典 - >字典组合。

The data structure I have in mind looks like dictionary --> dictionary --> array -- that is, country --> customer --> purchased. The plan is for there to be a new array per dictionary --> dictionary combination.

然而,当我尝试更新的阵列,它似乎被链接到所有下级字典 - >字典结构。也就是说,在第三行已被处理后,有以下的情况:

However, when I try to update the array, it seems that it is linked to all lower levels of the dictionary --> dictionary structure. That is, after the third row has been processed, have the following situation:

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

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

... whereas what I'm expecting to see is:

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

这里的code我试图使用方法:

Here's the code I'm attempting to use:

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

然而,这导致基本相同阵列由字典的每个最低水平被引用 - >字典结构。

这是我在做什么任何想法错了吗?

Any thoughts on what I'm doing wrong?

推荐答案

如果你在一个字典数组,您必须将其拉出字典,然后才能modifiy它。然后把它放回

If you have an array in a dictionary you must pull it out of the dictionary before you can modifiy it. Then put it back in.

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

这篇关于更新存储在VBA字典的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 23:59
查看更多