将键附加到嵌套字典Vba

时间:2018-01-18 11:41:07

标签: vba dictionary nested append

我正在使用嵌套字典来读取文件并存储数据。我在嵌套字典中有3个级别。每次我读取文件时,我都想更新第三个子字典。我们在Excel Vba中有一个选项吗? Python有一个选项appending-to-a-nested-dictionary但我真的需要它在excel vba中。如果我得到一个有用的提示,我将感激不尽。

我遵循了两种方法

Dict3.Add Key3, item3 
Dict2.Add Key2, Dict3
Dict1.add key1, Dict2

这种方法的问题是我无法将额外的密钥ex.Key4添加到Dict3。下面的另一种方法

Dict1(Key1).Dict2(Key2).Dict3.Add Key4, item4

导致运行时错误424.请建议我如何改进代码

1 个答案:

答案 0 :(得分:0)

这可能会让您更加困惑或困惑。 :)

你只需要参考字典键,例如Dict1(Key1)(Key2).Add Key4, item4

这与Dict1.Item(Key1).Item(Key2).Add Key4, item4相同,因为Item是默认成员。

Sub T()

    Dim m1 As Scripting.Dictionary, m2 As Scripting.Dictionary, m3 As Scripting.Dictionary
    Dim v1 As Variant, v2 As Variant, v3 As Variant

    Set m1 = New Scripting.Dictionary
    Set m2 = New Scripting.Dictionary
    Set m3 = New Scripting.Dictionary

    m3.Add "Three", "A" 'add A
    m2.Add "Two", m3
    m1.Add "One", m2

    m1("One")("Two").Add "Four", "B" 'add B
    m1("One")("Two").Add "Five", "C" 'add C

    For Each v1 In m1.Keys
        For Each v2 In m1(v1).Keys
            For Each v3 In m1(v1)(v2).Keys
                Debug.Print m1(v1)(v2)(v3)
            Next v3
        Next v2
    Next v1
End Sub

'A
'B
'C