创建集合作为字典的价值

时间:2019-07-09 10:48:45

标签: excel vba dictionary

我试图创建一个包含一个集合作为其值的Dictionary,因为我有多个具有不同数量属性的变量。我希望避免创建一个类。

Sub test()

    Set dict = CreateDict()

    Debug.Print "Done!"
End Sub

Private Function CreateDict() As Scripting.Dictionary
    Set dict = New Scripting.Dictionary
    dict.CompareMode = vbTextCompare


    Set wb = CreateObject("excel.Application").Workbooks.Open("S:\filename.xlsx")
    Set wks = wb.Worksheets(1)

    Row = 2
    Do While IsEmpty(wks.Cells(Row, 1)) = False

        key = wks.Cells(Row, 1)
        value = wks.Cells(Row, 3)

        'Debug.Print key, value

        If dict.Exists(key) Then
            dict(key).Add value
        Else
            Dim col As New Collection
            col.Add value
            dict.Add key, col
        End If

        Row = Row + 1
    Loop

    Workbooks("filename.xlsx").Close savechanges:=False

    Dim key1 As Variant
    For Each key1 In dict.Keys
        Debug.Print key1, dict(key1)(1)
    Next key1

    Set CreateDict = dict
End Function

我的密钥正确添加,但是当我尝试访问集合的第一个值时,它是空的,即使我在打印value之前也不为空。

我希望我不要犯一个愚蠢的错误,我一周前刚开始使用VBA。任何帮助将不胜感激,如果有更简单的方法或有现成的方法,我也将很高兴发现。

预先感谢

编辑:

对于任何人遗憾的是,如上所述,这是行不通的,因为VBA不会在每次应用Dim col As New Collection时创建一个新的Collection。而是将所有值仅添加到一个集合col中。但是,根据这篇文章Set variable name with string variable in VBA,我发现了一种解决方法,因为在VBA中无法使用动态变量名。

但是,我刚刚创建了一个函数,该函数创建并返回一个集合。我的代码现在如下所示:

Sub test()

    Set dict = CreateDict()

    Debug.Print "Done!"
End Sub

Private Function CreateDict() As Scripting.Dictionary
    Set dict = New Scripting.Dictionary
    dict.CompareMode = vbTextCompare


    Set wb = CreateObject("excel.Application").Workbooks.Open("S:\filename.xlsx")
    Set wks = wb.Worksheets(1)

    Row = 2
    Do While IsEmpty(wks.Cells(Row, 1)) = False

        key = wks.Cells(Row, 1)
        value = wks.Cells(Row, 3)

        'Debug.Print key, value

        If dict.Exists(key) Then
            dict(key).Add value
        Else
            dict.Add key, CreateCollection()
            dict(key).Add value
        End If

        Row = Row + 1
    Loop

    Workbooks("filename.xlsx").Close savechanges:=False

    Set CreateDict = dict
End Function

Private Function CreateCollection() As Collection
    Dim col As New Collection
    Set CreateCollection = col
End Function

1 个答案:

答案 0 :(得分:2)

代替dict(key1)(0),如下所示扩展代码:

Dim c as Collection
Set c = dict(key1)
Debug.Print c(1)    ' or c.item(1)

两个问题:

  • 从1
  • 开始对集合进行索引
  • 如果VBA没有类型信息,有时VBA无法正确解决链式方法调用。

https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/item-method-visual-basic-for-applications