在不向字典中添加键和项的情况下,测试VBA字典的Item是否等于给定值



我需要测试VBA字典的Item是否等于给定值,而不需要向字典添加新的键和值。

dict.RemoveAll
MsgBox dict.Exists(key)

MsgBox dict. exists (key)返回false, dict为空。

var = "Hello"
MsgBox var = dict(key)

MsgBox返回false,因为var和dict(key)返回的项不相等。但是当我再次检查键是否存在于字典中时,dict.Exists(key)现在返回true。

MsgBox dict.Exists(keys)

在我看来,相等操作符不仅将var与项目进行比较,而且还将新键和项目对分配给字典,但我需要字典仍然为空。我怎样才能做到这一点?

使用exists()检查键是否存在:

Sub foo()
Dim dict As Scripting.Dictionary
Dim key As String
key = "key1"
Set dict = New Dictionary
Debug.Print dict(key) ' -- create a value of Empty for the key
Debug.Print dict.Count ' -- 1 (yikes!)
Set dict = New Dictionary
Debug.Print dict.Exists(key) ' -- no side effects
Debug.Print dict.Count '-- 0 (great!)
End Sub

参见(感谢Cameron Critchlow):

scripting-dictionary-lookup-add-if-not-present-with-only-one-key-search

请注意,在您的问题中,您正在创建一个变量,然后检查它是否等于某个键的值(如果该键存在!)-因此通过使用上述方法的扩展,首先检查键是否存在,然后检查它是否与您的变量相同:

Dim other_key As String
Dim result As Boolean
other_key = "key2"
If dict.Exists(key) Then
If other_key = dict(key) Then
result = True
End If
End If
Debug.Print result

这些代码将测试所有键和项是否匹配,而不添加任何额外的键。

Dim Dict As Object
Set Dict = CreateObject("Scripting.Dictionary")
Dict.Add "test", "this"
Dim Var As String
Dim var2 As String
Var = "test"
var2 = "this"
Dim Key As Variant

For Each Key In Dict
Debug.Print "var - item", Var = Dict(Key)
Debug.Print "var - key", Var = Key
Debug.Print "var2 - item", var2 = Dict(Key)
Debug.Print "var2 - key", var2 = Key
Next Key

最新更新