Problem: I want to create a function that gets one string and returns a dictionary. After much reading in SO I reproduced exactly the code given in some questions and I end up with a solution that looks to work. But there are things that I dont understand.
here the code which is a bit long because includes some comments:
Private Sub testdictionary()
Dim dict_in_sub As Scripting.Dictionary
' Do I really need this??:
'Set dict_in_sub = New Scripting.Dictionary
' or this:
'Set dict_in_sub =CreateObject("Scripting.Dictionary")
Call returning_dict_func("word1.word2")
Set dict_in_sub = returning_dict_func("whatever.second")
MsgBox "in code:" & Chr(10) & dict_in_sub("A") & Chr(10) & dict_in_sub("B")
End Sub
This is the function called:
Function returning_dict_func(SC As String) As Scripting.Dictionary
' should this function return a dictionary or an object or a scrippting dictionary??
Dim dictionary_in_function
Set dictionary_in_function = CreateObject("Scripting.Dictionary")
'take the first and second part of the string separated by the period
dictionary_in_function("A") = Mid(SC, 1, InStr(SC, ".") - 1)
dictionary_in_function("B") = Mid(SC, InStr(SC, ".") + 1, Len(SC))
MsgBox dictionary_in_function("A") & Chr(10) & dictionary_in_function("B")
Set returning_dict_func = dictionary_in_function
End Function
Even if I got the code running, there are a few things that make returning a dict from a function in VBA strange Introducing the following changes into the code make it not working:
Dim dict_in_sub as Dictionary
' it does not work. What is the difference between dictionary and scrippting.dictionary?
' defining the function as returning a dictionary does not work
Function returning_dict_func(SC As String) As Dictionary
' if both are dictionaries it does not work
Dim dict_in_sub as Dictionary
Function returning_dict_func(SC As String) As Dictionary
Why is dictionary different than scripting.dictionary?
When should you initialize with
Set dict_modifiers = CreateObject("Scripting.Dictionary")
thanks
Note: I had a look to: a) VBA in Excel 2010: Scripting.Dictionary return value of a function won't pass as parameter to a wrapping function call b) Returning dictionary from function in vba. Error 450 c) Returning an dictionary object from a function in VBA