如何在Array中存储和访问Dictionary对象

时间:2018-06-11 05:09:47

标签: vba web-scraping

我想将字典对象存储在数组中,但是我收到错误。有什么办法可以在数组中存储字典

Sub aaa()

    Dim arr(5)
    'arr(0) = 100   
     Set dict_123 = CreateObject("Scripting.Dictionary")
     dict_123.Add "first", 300
     dict_123.Add "Second", 500    
     arr(0) = dict_123   

End Sub

错误是错误的参数数量或无效的属性赋值在" arr(0)= dict_123"

1 个答案:

答案 0 :(得分:1)

尝试以下

  1. 使用Option Explicit检查变量声明
  2. 将您的字典声明为Object
  3. 因为它是一个对象,所以在添加到数组
  4. 时需要使用set关键字

    <强>代码:

    Option Explicit
    
    Public Sub aaa()
    
        Dim arr(5)
        Dim dict_123 As Object
        Set dict_123 = CreateObject("Scripting.Dictionary")
        dict_123.Add "first", 300
        dict_123.Add "Second", 500
        Set arr(0) = dict_123
    
    End Sub
    

    修改

    作为功能

    Option Explicit
    Public Sub DoSomeThing()
        Dim dict As Object
        Set dict = aaa()(0)
        Dim key As Variant
        For Each key In dict.Keys
            Debug.Print dict(key)
        Next key
    End Sub
    
    Public Function aaa() As Variant
        Dim arr(5)
        Dim dict_123 As Object
        Set dict_123 = CreateObject("Scripting.Dictionary")
        dict_123.Add "first", 300
        dict_123.Add "Second", 500
        Set arr(0) = dict_123
        aaa = arr
    End Function