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

时间:2018-09-04 14:46:47

标签: 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

致谢

4 个答案:

答案 0 :(得分:2)

.exists()函数检查是否存在key。您正在搜索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

答案 1 :(得分:0)

@Kubie指出,Exists检查键而不是值。如果您在值和键之间具有1-1的对应关系,则可以维护两个字典,一个字典用于键到值的映射,另一个用于值到键的反向映射:

Sub Dict()

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

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

    Pako.Add "01", "first"

    If TunaItems.Exists(Pako.Items(0)) = True Then
        MsgBox ("exists") 'works as expected
    Else
        MsgBox ("not exists")
    End If
End Sub

如果对应关系不是一对一的,则第二个字典中的值可以是导致给定值的第一个键。当然,要确保两个字典保持同步。

答案 2 :(得分:0)

您还可以从一个词典的项目中生成一个数组,并使用Match来查看是否包含特定值(不及.Exists,但仅适用于S&G)

Option Explicit
Public Sub Dict()
    Dim Tuna As Scripting.Dictionary, Pako As Scripting.Dictionary, tunaArray
    Set Tuna = New Scripting.Dictionary
    Set Pako = New Scripting.Dictionary

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

    Pako.Add "01", "first"
    ReDim tunaArray(0 To Tuna.Count - 1)
    tunaArray = Tuna.Items

    If Not IsError(Application.match(Pako.Items(0), tunaArray, 0)) Then
        MsgBox "exists"
    Else
        MsgBox "not exists"
    End If
End Sub

答案 3 :(得分:-1)

谢谢,我完全错过了。然后可以检查第二个字典中是否存在第一个字典的关键字吗?我不想使用循环。