Sn_Srm
Sn_Srm

Reputation: 101

Cannot pass dictionary as an argument to a VBA function

I have a VBA function that is supposed to take a Dictionary as an argument:

Function ShowDict(Dict1 As Dictionary)
   For Each x In Dict1
        MsgBox (Dict1.Item(x))
   Next
End Function

And I am trying to call it the following way:

Dim Dict As Dictionary
Set Dict = Dictionary
Dict.Add "Owner", "John"
Dict.Add "Employee", "Sam"
ShowDict (Dict)

I did select Microsoft Scripting References from the References prior to defining the Dictionary. However, I get a compile error stating 'Argument not optional' when I try to call the function using 'Dict' as the parameter. Can anyone help me?

Upvotes: 4

Views: 2818

Answers (1)

HansUp
HansUp

Reputation: 97121

Make these 2 changes (New Dictionary and ShowDict Dict):

Dim Dict As Dictionary
'Set Dict = Dictionary
Set Dict = New Dictionary
Dict.Add "Owner", "John"
Dict.Add "Employee", "Sam"
'ShowDict (Dict)
ShowDict Dict

Also I suggest you add Option Explicit to the code module's Declarations section and include Dim x in your ShowDict function. The absence of those does not contribute to the immediate problem, but adding them could prevent other problems in the future.

Upvotes: 5

Related Questions