在函数中创建字典并在子函数中使用它

Create dictionary in function and use it in a sub

我试图在子函数中使用的函数中创建字典,但出现错误

"User defined type not defined".

不知道是不是很明显,就是看不出问题所在

我已经简化了代码来制作一个简单的代码:

Public Function create_dic(ByVal var As String) As Dictionary

   my_dic.CompareMode = vbTextCompare

   If var = "test" Then
       my_dic.Add Key:="var 1", Item:=1
   Else
       my_dic.Add Key:="var 2", Item:=2
   End If

   Set create_dic = my_dic
            
End Function
    

Sub prueba()
    Set respuesta = create_dic("test")
End Sub

您是否设置了对 “Microsoft 脚本运行时” 的引用? Dictionary 不是标准 VBA 的一部分,需要库。参见 VBA Dictionary References

同样,当您使用 my_dic.CompareMode 时,它还不存在。确保使用 Option Explicit 并正确声明所有变量。另外需要先新建一个字典对象才能使用

Option Explicit

Public Function create_dic(ByVal var As String) As Dictionary
   Dim my_dic As Dictionary  ' declare variable type
   Set my_dic = New Dictionary  ' create a new dictionary object

   my_dic.CompareMode = vbTextCompare

   If var = "test" Then
       my_dic.Add Key:="var 1", Item:=1
   Else
       my_dic.Add Key:="var 2", Item:=2
   End If

   Set create_dic = my_dic
            
End Function
    

Public Sub prueba()
    Dim respuesta As Dictionary  ' declare variable type
    Set respuesta = create_dic("test")
End Sub

有关词典的更多信息,这是一个很好的参考:Excel VBA Dictionary – A Complete Guide