lcardona89
lcardona89

Reputation: 9

Is it possible to add a dictionary to an array in Excel VBA?

I'm trying to figure out if this is a possibility in terms of the capability of excel. Consider the following code in what I'm trying to do:

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

The following is the line of code that gives me the error:

some_array_dict(i) = some_dict

Can anyone help with this?

Upvotes: 1

Views: 5519

Answers (3)

paulroho
paulroho

Reputation: 1266

Since Dictionary is an object, you have to use Set for the assignment:

Set some_array_dict(i) = some_dict ' No issue

Upvotes: 2

Tim Williams
Tim Williams

Reputation: 166196

Array is declared as wrong type, and you need to use Set when assigning objects

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

Upvotes: 4

jeffrey_t_b
jeffrey_t_b

Reputation: 1769

It looks like you are trying to assign a Dictionary to a string array.

Try:

ReDim some_array_dict(y) As Dictionary

Upvotes: 2

Related Questions