vba: return dictionary from function

jason m picture jason m · Oct 27, 2010 · Viewed 25k times · Source

this outlines what i am trying to do.

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

thank you in advance for any and all help.

        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

Answer

BradC picture BradC · Oct 27, 2010

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.