Getting a specific value from a dictionary in a function
11:22 16 Jan 2023

I want to use a function to store a dictionary of values that I will use repeatedly in other spreadsheets. Therefore to call this function that contains the dictionary, would be extremely useful. However, I'm unable to get an Item value back from the function by passing a Key value. It seems to work for the Debug.Print, but when I try it without the Debug.Print, it throws an error.

Function location_Dict(loc_Code)

    Dim loc_dict As Dictionary
    Set loc_dict = New Dictionary
    
    Debug.Print "In loc_dic and value is " & loc_Code
    
    With loc_dict()
    
        .Add Key:=21, Item:="Alamo, TN"
        .Add Key:=27, Item:="Bay, AR"
        .Add Key:=54, Item:="Cash, AR"
        .Add Key:=3, Item:="Clarkton, MO"
        .Add Key:=42, Item:="Dyersburg, TN"
        .Add Key:=2, Item:="Hayti, MO"
        .Add Key:=59, Item:="Hazel, KY"
        .Add Key:=44, Item:="Hickman, KY"
        .Add Key:=56, Item:="Leachville, AR"
        .Add Key:=90, Item:="Senath, MO"
        .Add Key:=91, Item:="Walnut Ridge, AR"
        .Add Key:=87, Item:="Marmaduke, AR"
        .Add Key:=12, Item:="Mason, TN"
        .Add Key:=14, Item:="Matthews, MO"
        .Add Key:=51, Item:="Newport, AR"
        .Add Key:=58, Item:="Ripley, TN"
        .Add Key:=4, Item:="Sharon, TN"
        .Add Key:=72, Item:="Halls, TN"
        .Add Key:=13, Item:="Humboldt, TN"
        .Add Key:=23, Item:="Dudley, MO"
    
    End With

    Debug.Print loc_dict.Item(loc_Code)

End Function

When I pass loc_Code as "51" as an example to the function, if I try to use loc_dict.Item(loc_Code)
to return the dictionary Item without Debug.Print it doesn't accept it.

excel vba function dictionary