VBA 在字典中存储 ArrayList

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

我需要一个字典,其中包含一个带有相应日期对的键。我创建了下面的代码来说明我现在正在做的事情。所以基本上,我将这对日期存储在 ArrayList 中,然后将其添加到我的字典中。然后,我从 ArrayList 中删除这些项目,以便可以再次使用它来存储下一对日期。 当我想在代码的其他部分使用 myDict 时,字典包含键,但不包含相应的日期对。 我认为这与通过引用传递 ArrayList (?) 和我应用的 Clear 函数有关。

我该如何解决这个问题?我并不特别需要使用 ArrayList 来存储这对日期。

Function myDict() As Object

    Dim dict As Object, keyList As Object, arrListToDict As Object
    Dim keyListCount As Long, iLoop As Long
    Dim dateToday As Date, date1 As Date, date2 As Date
    Dim x As Long
    
    Set dict = CreateObject("Scripting.Dictionary")
    Set keyList = CreateObject("System.Collections.ArrayList")
    Set arrListToDict = CreateObject("System.Collections.ArrayList")
    
    keyList.Add ("Hey")
    keyList.Add ("Hello")
    keyListCount = keyList.Count
    dateToday = Date

    
    For iLoop = 0 To keyListCount - 1
        date1 = DateAdd("d", Int(20000 * Rnd), dateToday)
        date2 = DateAdd("d", Int(20000 * Rnd), dateToday)
        arrListToDict.Add (date1)
        arrListToDict.Add (date2)
        dict.Add key:=keyList(iLoop), Item:=arrListToDict
        
        arrListToDict.Clear
    Next iLoop
    
    Set myDict = dict

End Function

我用谷歌搜索但找不到解决方案。

vba dictionary arraylist
1个回答
0
投票

在字典中嵌套数组列表

  • 对于每个字典键,创建一个新的数组列表。
Function myDict() As Object
    
    Dim keyList As Object:
    Set keyList = CreateObject("System.Collections.ArrayList")
    keyList.Add ("Hey")
    keyList.Add ("Hello")
    
    Dim dateToday As Date: dateToday = Date
    
    Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
    
    Dim arrList As Object, i As Long, date1 As Date, date2 As Date
    
    For i = 0 To keyList.Count - 1
        date1 = DateAdd("d", Int(20000 * Rnd), dateToday)
        date2 = DateAdd("d", Int(20000 * Rnd), dateToday)
        Set arrList = CreateObject("System.Collections.ArrayList")
        arrList.Add (date1)
        arrList.Add (date2)
        dict.Add Key:=keyList(i), Item:=arrList
    Next i
    
    Set myDict = dict

End Function
Sub Test()
    Dim dict As Object: Set dict = myDict
    Dim Key As Variant, Item As Variant
    For Each Key In dict.Keys
        Debug.Print Key
        For Each Item In dict(Key)
            Debug.Print vbTab & Item
        Next Item
    Next Key
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.