是否可以在Excel VBA中向数组添加字典?

时间:2014-06-19 20:22:38

标签: arrays excel vba excel-vba dictionary

我试图弄清楚这是否有可能在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

任何人都可以帮忙吗?如果您需要对此进行任何澄清,请与我们联系。

感谢先进的帮助。

3 个答案:

答案 0 :(得分:3)

数组被声明为错误类型,您需要在分配对象时使用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

答案 1 :(得分:1)

看起来您正在尝试将字典分配给字符串数组。

尝试:

ReDim some_array_dict(y) As Dictionary

答案 2 :(得分:1)

由于Dictionary是一个对象,您必须使用Set进行分配:

Set some_array_dict(i) = some_dict ' No issue