0

I would like to store dictionary object in array but I am getting an error. is there any way which I can store dictionary in array

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

Error is Wrong number of Arguments or invalid property assignment at "arr(0) = dict_123 "

1
  • 1
    You want to store an object reference, you need to Set that reference. Set arr(0) = dict_123. Commented Jun 11, 2018 at 5:18

1 Answer 1

1

Try the following

  1. Use Option Explicit to check variable declarations
  2. Declare your dictionary as Object
  3. As it is an object you need to use the set keyword when adding to array

Code:

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

Edit:

As function

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
Sign up to request clarification or add additional context in comments.

3 Comments

if I write "aaa" as function and called it from the other sub. how can I return the array and how can I access the dictionary data in the sub?
Can't we loop over the Dictionary in DoSomeThing like For Each k In dict.keys dict (k) Next I am getting an error Object doesn't support this property at dict(k)
@ QHarr, stackoverflow.com/questions/50792960/… can you please help me from the question mention in link. because of the space I opened one more question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.