I declare a Dictionary in VBA and fill it in with keys and values:
Sub UseDictionary()
Dim Z As New Dictionary
Z.Add key:="Norway", Item:="AAA"
Z.Add key:="Germany", Item:="AA"
Z.Add key:="USA", Item:="A"
Z.Add key:="France", Item:="AC"
Z.Add key:="Spain", Item:="B"
Z.Add key:="Greece", Item:="BC"
Dim numItems As Integer
numItems = Z.Count
MsgBox "The collection has " & numItems & " items."
End Sub
When I try to create a Function that sends back a value for a given key (a rating for a given country), it displays a #Value! error on my Excel sheet:
Function GetValueFromDict(Z As Object, key As String) As Variant
Dim dict As New Scripting.Dictionary
Set dict = Z
If dict.Exists(key) Then
GetValueFromDict = dict.Item(key)
Else
GetValueFromDict = Null
End If
End Function
Use a Dictionary UDF
In Excel
Use e.g. the formula
If you want the function to return an empty string when the country is not found, declare its result
As String(instead ofAs Variant) and remove the Else clause.In VBA