vbaexcelexcel-2003

How can I return a dictionary from a function?


This is not working for me, and it is unclear why.

Sub mySub()
    dim myDict as Dictionary
    myDict=new Dictionary
            
    myDict=myFunc()
                
End Sub
        
Function myFunc()
    dim myDict2
    set myDict2 = new Dictionary
                    
    'some code that does things and adds to myDict2'
                    
    myFunc=myDict2
End Function

How can I return a dictionary from a function?


Solution

  • You'll need to use the SET keyword anytime you are assigning an object instead of a value:

        Sub mySub()
            dim myDict as Dictionary
            set myDict = myFunc()
        End Sub
    
        Function myFunc() as Dictionary
            dim myDict2 as Dictionary
            set myDict2 = new Dictionary
                    'some code that does things and adds to myDict2'
            set myFunc=myDict2
        End Function
    

    Your original code was also creating myDict as a new Dictionary object, then immediately replacing it with a different one. You can just skip that step.