VBA /如何检查字典项是否存在于另一个字典中?

Slo*_*ep_ 1 arrays excel vba dictionary

我需要在 VBA 中有两个字典,我想检查第二个字典中是否存在第一个字典中的一项。我尝试了下面的代码,但没有找到该项目。仅出现消息“不存在”。有人可以帮忙吗?

Sub Dict()

Dim Tuna As Scripting.Dictionary
Set Tuna = New Scripting.Dictionary
Dim Pako As Scripting.Dictionary
Set Pako = New Scripting.Dictionary

Tuna.Add "01", "first"
Tuna.Add "02", "second"

Pako.Add "01", "first"

If Tuna.Exists(Pako.Items(0)) = True Then
MsgBox ("exists")
Else
MsgBox ("not exists")

End If
End Sub
Run Code Online (Sandbox Code Playgroud)

问候

Kub*_*bie 5

.exists()函数检查 a 是否key存在。您正在搜索 an item,因此您需要使用循环并检查字典中的每个项目。

例如:

Sub Test()

    Dim item As Variant  
    Dim Tuna As Scripting.Dictionary
    Dim Pako As Scripting.Dictionary

    Set Pako = New Scripting.Dictionary
    Set Tuna = New Scripting.Dictionary

    Tuna.Add "01", "first"
    Tuna.Add "02", "second"
    Pako.Add "01", "first"

    For each item in Tuna.Items
        If item = Pako("01") Then

            ' do something

            Exit For
        End If
    Next

End Sub
Run Code Online (Sandbox Code Playgroud)