【问题标题】:Appending keys to Nested Dictionary Vba将键附加到嵌套字典 Vba
【发布时间】:2018-06-27 11:29:08
【问题描述】:

我正在使用嵌套字典来读取文件并存储数据。我在嵌套字典中有 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。请建议我如何改进代码

【问题讨论】:

    标签: vba dictionary nested append


    【解决方案1】:

    这可能会帮助您或使您更加困惑。 :)

    您只需要参考字典键,例如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
    

    【讨论】:

    • @Raghu 考虑一个自定义字典包装类 - 它会更容易阅读和维护。
    猜你喜欢
    • 1970-01-01
    • 2021-08-26
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 2022-08-12
    • 2020-06-01
    • 2019-02-11
    • 2019-09-20
    相关资源
    最近更新 更多