vbaSub TestDictionary() Dim dict As Collection Set dict = New Collection ' 添加项到字典 dict.Add "Apple", "A" dict.Add "Banana", "B" dict.Add "Orange", "O" ' 判断字典中是否存在某个键 If KeyExists(dict, "A") Then MsgBox "键存在" Else MsgBox "键不存在" End IfEnd SubFunction KeyExists(ByVal dict As Collection, ByVal key As Variant) As Boolean Dim item As Variant On Error Resume Next item = dict(key) KeyExists = (Err.Number = 0) On Error GoTo 0End Function
vbaSub TestDictionary() Dim dict As Collection Set dict = New Collection ' 添加项到字典 dict.Add "Apple", "A" dict.Add "Banana", "B" dict.Add "Orange", "O" ' 判断字典中是否存在某个键 If KeyExists(dict, "A") Then MsgBox "键存在" Else MsgBox "键不存在" End IfEnd SubFunction KeyExists(ByVal dict As Collection, ByVal key As Variant) As Boolean Dim item As Variant On Error Resume Next item = dict(key) KeyExists = (Err.Number = 0) On Error GoTo 0End Function