gpt4 book ai didi

excel - 检查某个键是否在 Excel VBA 集合中的通用方法

转载 作者:行者123 更新时间:2023-12-01 18:45:48 25 4
gpt4 key购买 nike

我的代码中有不同的集合。有些包含对象(各种类型),其他则包含类型(例如 Long)。

有没有办法检查集合中是否包含适用于类型和对象的键?

到目前为止我有两个函数。

第一个函数:

Private Function ContainsObject(objCollection As Object, strName As String) As Boolean
Dim o As Object
On Error Resume Next
Set o = objCollection(strName)
ContainsObject = (Err.Number = 0)
Err.Clear
End Function

第二个函数:

Private Function ContainsLong(AllItems As Collection, TheKey As String) As Boolean
Dim TheValue As Long
On Error Resume Next
TheValue = AllItems.Item(TheKey)
ContainsLong = (Err.Number = 0)
Err.Clear
End Function

这两个函数的原因是,如果我传递一个具有 Longs 对的 Co​​llection(该函数总是返回 False),ContainsObject 似乎不起作用。

P.S.:第一个函数是 Test or check if sheet exists 中第三个答案的副本

最佳答案

您应该在第一个函数中使用Variant。您可以将Object分配给Variant,例如这不会出错:

Sub Test()
Dim var As Variant
Dim obj As Object
Set obj = Application
var = Application
Debug.Print var
End Sub

但这会产生类型不匹配编译错误,即尝试将Long分配给对象:

Sub Test()
Dim obj As Object
Dim lng As Long
lng = 3
Set obj = lng
End Sub

因此,对于通用函数(沿着代码行)检查 Collection 键是否有效,您可以使用:

Function HasKey(coll As Collection, strKey As String) As Boolean
Dim var As Variant
On Error Resume Next
var = coll(strKey)
HasKey = (Err.Number = 0)
Err.Clear
End Function

测试代码:

Sub Test()
Dim coll1 As New Collection
coll1.Add Item:=Sheet1.Range("A1"), Key:="1"
coll1.Add Item:=Sheet1.Range("A2"), Key:="2"
Debug.Print HasKey(coll1, "1")

Dim coll2 As New Collection
coll2.Add Item:=1, Key:="1"
coll2.Add Item:=2, Key:="2"
Debug.Print HasKey(coll2, "1")
End Sub

有一篇关于 MSDN 的有用文章关于这一点。上下文是 VB6,但与 VBA 相关。

关于excel - 检查某个键是否在 Excel VBA 集合中的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38007844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com