【问题标题】:Is it possible to add a dictionary to an array in Excel VBA?是否可以将字典添加到 Excel VBA 中的数组?
【发布时间】:2014-06-19 20:22:37
【问题描述】:

我试图弄清楚这是否是 excel 能力方面的一种可能性。在我正在尝试做的事情中考虑以下代码:

Dim some_text, split_text() As String
Dim some_array_dict() As String 'This is the array to store the dictionaries
Dim some_dict As Dictionary 'The dictionaries that I'll be storing in the array above

ReDim some_array_dict(y) As String 'y is previously defined as an integer

For i = 0 To y - 1
    Set some_dict = New Dictionary

    some_text = some_array(2, i)
    split_text = Split(some_text, " ")

    For j = 0 To UBound(split_text)
        some_dict.Add split_text(j), 1
    Next j

    some_array_dict(i) = some_dict 'Issue

    Debug.Print some_array_dict(i) 'For debugging purposes
Next i

以下是给我错误的代码行:

some_array_dict(i) = some_dict

有人可以帮忙吗?如果您需要对此进行任何澄清,请告诉我。

感谢您的帮助。

【问题讨论】:

  • 我认为 Tim 的解决方案是唯一真正有效的解决方案。请小心,因为Dictionary is a reference type 所以将每个数组组件设置为同一个对象将导致所有数组组件引用同一个对象。我不认为这是你想要的..
  • 更具体地说,对于蒂姆的回答,我必须将 Dim 作为 Dictionary。这实际上最终解决了我面临的问题。感谢您的帮助!

标签: arrays vba excel dictionary


【解决方案1】:

数组被声明为错误类型,分配对象时需要使用Set

Sub Tester()

    Dim arr_dict() As Object, x As Long

    ReDim arr_dict(1 To 3)
    For x = 1 To 3

        Set arr_dict(x) = CreateObject("scripting.dictionary")

        With arr_dict(x)
            .Add "hello", 1
            .Add "there", 2
        End With

    Next x

End Sub

【讨论】:

    【解决方案2】:

    您似乎正在尝试将 Dictionary 分配给 string 数组。

    试试:

    ReDim some_array_dict(y) As Dictionary
    

    【讨论】:

    • 这最终成为我特别面临的问题。感谢您的帮助!
    【解决方案3】:

    由于Dictionary 是一个对象,因此您必须使用Set 进行赋值:

    Set some_array_dict(i) = some_dict ' No issue
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-20
      • 1970-01-01
      • 2013-07-06
      • 2014-04-14
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多