Excel VBA – Dictonary.Exists(Dictionary)?
想更好地了解如何比较对象types的键。 dicOverall.exists(dic2)
返回False
而dicOverall.exists(dic1)
返回True
。 我不太清楚如何.Exists
比较的东西(循环?),但无论如何,我可以得到.Exists(dic2)
返回True
? 谢谢!
Sub test() Dim dic1 As Object Dim dic2 As Object Dim dicOverall As Object Set dic1 = CreateObject("scripting.dictionary") Set dic2 = CreateObject("scripting.dictionary") Set dicOverall = CreateObject("scripting.dictionary") dic1("Hi") = 1 dic1("Hello") = 1 dic2("Hi") = 1 dic2("Hello") = 1 dicOverall(dic1) = 1 Debug.Print dicOverall.exists(dic2) End Sub
我想如果你这样做
dicOverall(dic1) = 1
那么dicOverall
唯一存在的关键是对象dic1
并且您询问dic2
存在关键dicOverall
? 答案不可能是true
它总是false
。
即使它们包含相同的键, dic1
和dic2
也是2个完全不同的对象。 .exists
不会比较这些对象的内容,只是看到这些对象是不同的对象。
例:
比方说, .exists
检查一个特定的对象是否在一个盒子里,并且你有两个叫做dic1
和dic2
苹果。 如果你把苹果dic1
放入盒子,并检查与.exists
如果苹果dic2
是在框中,你会得到一个没有。 .exists
不检查框中是否有苹果,它检查是否有一个名为dic2
的特定苹果在框中。 即使它们都是苹果,看起来也一样。
Sub AppleExample() Dim apple1 As Object Dim apple2 As Object Dim box As Object Set apple1 = CreateObject("scripting.dictionary") Set apple2 = CreateObject("scripting.dictionary") Set box = CreateObject("scripting.dictionary") 'apple1 has 1 stem and a red color apple1("stem") = 1 apple1("redColor") = 1 'apple2 has 1 stem and a red color apple2("stem") = 1 apple2("redColor") = 1 'put apple1 into the box box(apple1) = 1 'check if apple2 is in the box Debug.Print box.exists(apple2) End Sub
如果你想检查盒子里是否有东西,看起来像apple1
但实际上是apple2
那么你必须自己检查所有的属性(干,颜色,…)。
如果你想检查是否dic1
与dic1
有相同的键,那么你必须检查…
- 如果
dic1
和dic2
具有相同的密钥计数(如果dic2
具有来自dic1
所有密钥,但加上其他密钥,则必须!) - 如果第一个是真的,然后遍历所有的
dic1
密钥,并检查每个单一的密钥是否存在于dic2
。
这里是一个很好的关于字典的资源: VBA字典和在VBA中使用字典类
我能想到得到.Exists(dic2)
返回True
的唯一方法就是将dic2
设置为引用dic1
– 所以在引擎盖下, dic1
和dic2
只是指向同一个基础对象的指针。
然后 – 即使您从不执行dicOverall.Add dic2, 1
如果您执行dicOverall.Exists(dic2)
dicOverall.Add dic2, 1
您仍将获得True
。
这完全不是一个真正的应用程序 – 但是如果你正在玩字典,那么这个程序会很有用。 在这个示例代码中,您将看到使用Set dic2 = dic1
使它们指向相同的底层字典。 而且改变dic2
的值也会在dic1
改变它 – 表明它们是指向同一事物的指针。
然后检查dic2
是否是dic2
的关键字将返回True
:
Option Explicit Sub Test() Dim dic1 As New Dictionary Dim dic2 As New Dictionary Dim dicOverall As New Dictionary 'add items to first dictionary dic1.Add "foo", "bar" dic1.Add "baz", "qux" 'make second refer to first Set dic2 = dic1 'add first dictionary to overall dicOverall.Add dic1, 1 'change a value in 2nd dictionary and see 1st dictionary change too Debug.Print dic1.Item("baz") dic2.Item("baz") = "hello world" Debug.Print dic1.Item("baz") 'shows 1 for both dictionaries '*even though you never added dic2 to dicOverall* Debug.Print dicOverall.Exists(dic1) Debug.Print dicOverall.Exists(dic2) End Sub
我的debugging输出:
qux hello world True True