我在我目前的工作场所继承了一个大型VB6应用程序.我在工作中学习VB6,我遇到了很多问题.目前的主要问题是我无法弄清楚如何检查Collection对象中是否存在密钥.有人可以帮忙吗?
我的标准功能非常简单.无论元素类型如何,这都可以工作,因为它不需要做任何赋值,它只执行集合属性get.
Public Function Exists(ByVal oCol As Collection, ByVal vKey As Variant) As Boolean On Error Resume Next oCol.Item vKey Exists = (Err.Number = 0) Err.Clear End Function
@Mark Biek你的keyExists与我的标准Exists()函数非常匹配.为了使类对COM公开的集合更有用并检查数字索引,我建议将sKey和myCollection更改为不键入.如果该函数将与一组对象一起使用,则需要'set'(在设置val的行上).
编辑:我从来没有注意到基于对象和基于值的Exists()函数的不同要求.我很少将集合用于非对象,但这似乎是一个完美的瓶颈,当我需要检查存在时,这个bug很难被追踪.如果错误处理程序已处于活动状态,则错误处理将失败,因此需要两个函数来获取新的错误范围.只需要调用Exists()函数:
Public Function Exists(col, index) As Boolean On Error GoTo ExistsTryNonObject Dim o As Object Set o = col(index) Exists = True Exit Function ExistsTryNonObject: Exists = ExistsNonObject(col, index) End Function Private Function ExistsNonObject(col, index) As Boolean On Error GoTo ExistsNonObjectErrorHandler Dim v As Variant v = col(index) ExistsNonObject = True Exit Function ExistsNonObjectErrorHandler: ExistsNonObject = False End Function
并验证功能:
Public Sub TestExists() Dim c As New Collection Dim b As New Class1 c.Add "a string", "a" c.Add b, "b" Debug.Print "a", Exists(c, "a") ' True ' Debug.Print "b", Exists(c, "b") ' True ' Debug.Print "c", Exists(c, "c") ' False ' Debug.Print 1, Exists(c, 1) ' True ' Debug.Print 2, Exists(c, 2) ' True ' Debug.Print 3, Exists(c, 3) ' False ' End Sub
我总是用这样的函数完成它:
public function keyExists(myCollection as collection, sKey as string) as Boolean on error goto handleerror: dim val as variant val = myCollection(sKey) keyExists = true exit sub handleerror: keyExists = false end function
正如Thomas所指出的,你需要设置一个对象而不是Let.这是我的库中的一个通用函数,适用于值和对象类型:
Public Function Exists(ByVal key As Variant, ByRef col As Collection) As Boolean 'Returns True if item with key exists in collection On Error Resume Next Const ERR_OBJECT_TYPE As Long = 438 Dim item As Variant 'Try reach item by key item = col.item(key) 'If no error occurred, key exists If Err.Number = 0 Then Exists = True 'In cases where error 438 is thrown, it is likely that 'the item does exist, but is an object that cannot be Let ElseIf Err.Number = ERR_OBJECT_TYPE Then 'Try reach object by key Set item = col.item(key) 'If an object was found, the key exists If Not item Is Nothing Then Exists = True End If End If Err.Clear End Function
正如Thomas所建议的那样,您可以将Collection类型更改为Object以对此进行概括..Item(key)语法由大多数集合类共享,因此实际上可能很有用.
编辑好像我被托马斯自己打得有点殴打.但是为了更容易重用,我个人更喜欢没有私有依赖的单个函数.