Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vba: return dictionary from function

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
like image 584
jason m Avatar asked Oct 27 '10 21:10

jason m


People also ask

How do you define a dictionary in VBA?

Excel VBA Dictionary. Using VBA Dictionary we can group all kinds of data in a dictionary to get access to all the items with a single variable. We can use the dictionary to create a collection of key-value combinations. Once the object is linked to keys, later on, we can call them by just using the key name.


1 Answers

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.

like image 62
BradC Avatar answered Oct 06 '22 12:10

BradC