VBA - 访问嵌套字典中的项目

问题描述 投票:0回答:1

我在名为“Mapping”的 Excel 工作表中列出了下表

资金 投资组合 结构 位置账户
F1 基金1 现金 Acct_1
F2 基金2 现金 Acct_2
F3 基金3 现金 Acct_3

在下面的代码中,我试图创建一个字典的字典,但是最后一行代码抛出了一个错误:424需要对象。 如何访问字典中的元素?

Sub build_dictionary()
    
    
    Dim funds As Scripting.Dictionary
    Dim mapping As Scripting.Dictionary
    Dim fund As Variant
    
    'funds represents the outer dictionary
    Set funds = New Scripting.Dictionary
    
    'mapping represents the inner dictionary
    Set mapping = New Scripting.Dictionary
    
    For Each fund In Worksheets("Mapping").Range("A2", Range("a2").End(xlDown)).Cells
        
        'set key value pairs to the mapping(inner) dictionary
        mapping.Add "portfolio", fund.Offset(0, 1).Value
        mapping.Add "structure", fund.Offset(0, 2).Value
        mapping.Add "locationaccount", fund.Offset(0, 3).Value
        
        'in the outer dictionary set key=fund, item = mapping dictionary
        funds.Add fund, mapping
        
        'remove all key-value pairs of mapping dictionary in preparation of next loop
        mapping.RemoveAll
           
    Next fund
    
    'produces error '424' Object required
    Debug.Print funds("F1").Item("portfolio")
    

End Sub
excel vba dictionary nested
1个回答
0
投票

你的内部字典都指向同一个对象

mapping
,并且你每次循环都会清除它,所以你的内部字典是空的。

每次制作一本新词典:

Sub build_dictionary()
    
    Dim funds As Scripting.Dictionary
    Dim fund As Range, fundName As String
    
    Set funds = New Scripting.Dictionary 'funds represents the outer dictionary
    
    For Each fund In Worksheets("Mapping").Range("A2", Range("a2").End(xlDown)).Cells
        fundName = fund.Value
        funds.Add fundName, New Scripting.Dictionary 'create a fresh dict
        With funds(fundName) 'set key value pairs to the inner dictionary
            .Add "portfolio", fund.Offset(0, 1).Value
            .Add "structure", fund.Offset(0, 2).Value
            .Add "locationaccount", fund.Offset(0, 3).Value
        End With
    Next fund
    
    Debug.Print funds("F1").Item("portfolio") '>> Fund 1
    Debug.Print funds("F2").Item("structure") '>> Cash
    
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.