检查VB6集合中是否存在记录?
我在当前工作场所继承了一个大型VB6应用程序。我在工作中学习了VB6,我遇到了很多问题。目前的主要问题是我不知道如何检查集合对象中是否存在键。有人能帮忙吗?我总是用这样的函数来完成:检查VB6集合中是否存在记录?,vb6,collections,Vb6,Collections,我在当前工作场所继承了一个大型VB6应用程序。我在工作中学习了VB6,我遇到了很多问题。目前的主要问题是我不知道如何检查集合对象中是否存在键。有人能帮忙吗?我总是用这样的函数来完成: public function keyExists(myCollection as collection, sKey as string) as Boolean on error goto handleerror: dim val as variant val = myCollection(sKey
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
Public Function Exists(col, index) As Boolean
Dim v As Variant
TryObject:
On Error GoTo ExistsTryObject
Set v = col(index)
Exists = True
Exit Function
TryNonObject:
On Error GoTo ExistsTryNonObject
v = col(index)
Exists = True
Exit Function
ExistsTryObject:
' This will reset your Err Handler
Resume TryNonObject
ExistsTryNonObject:
Exists = False
End Function
@Mark Biek您的keyExists与我的标准Exists()函数非常匹配。为了使该类对COM公开的集合和检查数字索引更有用,我建议将sKey和myCollection更改为不键入。如果函数将用于对象集合,则需要“set”(在设置val的行上) 编辑:我从来没有注意到对基于对象和基于值的Exists()函数的不同要求,这让我感到困扰。我很少对非对象使用集合,但这似乎是一个缺陷的完美瓶颈,当我需要检查是否存在时,很难找到它。由于如果错误处理程序已处于活动状态,则错误处理将失败,因此需要两个函数来获取新的错误范围。只需调用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
正如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所建议的,您可以将集合类型更改为Object来概括它。.Item(key)语法由大多数集合类共享,因此这实际上可能很有用
编辑我好像是被托马斯自己打败了。但是,为了便于重用,我个人更喜欢没有私有依赖项的单个函数。使用错误处理程序捕获密钥不存在于集合中的情况会使使用“所有错误时中断”选项进行调试变得非常烦人。为了避免不必要的错误,我经常创建一个类,该类在集合中包含存储的对象,在字典中包含所有键。Dictionary有exists(key)-函数,所以我可以在尝试从集合中获取对象之前调用它。您只能在字典中存储字符串,因此如果您需要存储对象,仍然需要一个集合。更好的解决方案是编写TryGet函数。很多时候,你要检查是否存在,然后获取项目。同时做可以节省时间
public Function TryGet(key as string, col as collection) as Variant
on error goto errhandler
Set TryGet= col(key)
exit function
errhandler:
Set TryGet = nothing
end function
看
这里的实现的优点是还可以选择性地返回找到的元素,并且可以处理对象/本机类型(根据注释)
由于链接不再可用,在此复制:
确定集合中是否存在项
下面的代码显示如何确定集合中是否存在项
Option Explicit
'Purpose : Determines if an item already exists in a collection
'Inputs : oCollection The collection to test for the existance of the item
' vIndex The index of the item.
' [vItem] See Outputs
'Outputs : Returns True if the item already exists in the collection.
' [vItem] The value of the item, if it exists, else returns "empty".
'Notes :
'Example :
Function CollectionItemExists(vIndex As Variant, oCollection As Collection, Optional vItem As Variant) As Boolean
On Error GoTo ErrNotExist
'Clear output result
If IsObject(vItem) Then
Set vItem = Nothing
Else
vItem = Empty
End If
If VarType(vIndex) = vbString Then
'Test if item exists
If VarType(oCollection.Item(CStr(vIndex))) = vbObject Then
'Return an object
Set vItem = oCollection.Item(CStr(vIndex))
Else
'Return an standard variable
vItem = oCollection.Item(CStr(vIndex))
End If
Else
'Test if item exists
If VarType(oCollection.Item(Int(vIndex))) = vbObject Then
'Return an object
Set vItem = oCollection.Item(Int(vIndex))
Else
'Return an standard variable
vItem = oCollection.Item(Int(vIndex))
End If
End If
'Return success
CollectionItemExists = True
Exit Function
ErrNotExist:
CollectionItemExists = False
On Error GoTo 0
End Function
'Demonstration routine
Sub Test()
Dim oColl As New Collection, oValue As Variant
oColl.Add "red1", "KEYA"
oColl.Add "red2", "KEYB"
'Return the two items in the collection
Debug.Print CollectionItemExists("KEYA", oColl, oValue)
Debug.Print "Returned: " & oValue
Debug.Print "-----------"
Debug.Print CollectionItemExists(2, oColl, oValue)
Debug.Print "Returned: " & oValue
'Should fail
Debug.Print CollectionItemExists("KEYC", oColl, oValue)
Debug.Print "Returned: " & oValue
Set oColl = Nothing
End Sub
- 更多信息,请访问:
- 我的标准功能非常简单。无论元素类型如何,这都可以工作,因为它不需要执行任何赋值,它只执行集合属性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
语句“如果错误处理程序已处于活动状态,则错误处理将失败”仅部分正确
在例程中可以有多个错误处理程序。因此,可以在一个功能中容纳相同的功能。
只需像这样重写代码:
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
Public Function Exists(col, index) As Boolean
Dim v As Variant
TryObject:
On Error GoTo ExistsTryObject
Set v = col(index)
Exists = True
Exit Function
TryNonObject:
On Error GoTo ExistsTryNonObject
v = col(index)
Exists = True
Exit Function
ExistsTryObject:
' This will reset your Err Handler
Resume TryNonObject
ExistsTryNonObject:
Exists = False
End Function
但是,如果只将代码合并到例程的TryNonObject部分,则会产生相同的信息。对于对象和非对象,它都将成功。
但是,它将加快非对象代码的速度,因为您只需执行一条语句即可断言该项存在于集合中。在查找类似于此的函数时,我将其设计为如下所示。
Option Explicit
'Purpose : Determines if an item already exists in a collection
'Inputs : oCollection The collection to test for the existance of the item
' vIndex The index of the item.
' [vItem] See Outputs
'Outputs : Returns True if the item already exists in the collection.
' [vItem] The value of the item, if it exists, else returns "empty".
'Notes :
'Example :
Function CollectionItemExists(vIndex As Variant, oCollection As Collection, Optional vItem As Variant) As Boolean
On Error GoTo ErrNotExist
'Clear output result
If IsObject(vItem) Then
Set vItem = Nothing
Else
vItem = Empty
End If
If VarType(vIndex) = vbString Then
'Test if item exists
If VarType(oCollection.Item(CStr(vIndex))) = vbObject Then
'Return an object
Set vItem = oCollection.Item(CStr(vIndex))
Else
'Return an standard variable
vItem = oCollection.Item(CStr(vIndex))
End If
Else
'Test if item exists
If VarType(oCollection.Item(Int(vIndex))) = vbObject Then
'Return an object
Set vItem = oCollection.Item(Int(vIndex))
Else
'Return an standard variable
vItem = oCollection.Item(Int(vIndex))
End If
End If
'Return success
CollectionItemExists = True
Exit Function
ErrNotExist:
CollectionItemExists = False
On Error GoTo 0
End Function
'Demonstration routine
Sub Test()
Dim oColl As New Collection, oValue As Variant
oColl.Add "red1", "KEYA"
oColl.Add "red2", "KEYB"
'Return the two items in the collection
Debug.Print CollectionItemExists("KEYA", oColl, oValue)
Debug.Print "Returned: " & oValue
Debug.Print "-----------"
Debug.Print CollectionItemExists(2, oColl, oValue)
Debug.Print "Returned: " & oValue
'Should fail
Debug.Print CollectionItemExists("KEYC", oColl, oValue)
Debug.Print "Returned: " & oValue
Set oColl = Nothing
End Sub
这应该适用于对象和非对象,而无需指定新变量
Public Function Exists(ByRef Col As Collection, ByVal Key) As Boolean
On Error GoTo KeyError
If Not Col(Key) Is Nothing Then
Exists = True
Else
Exists = False
End If
Exit Function
KeyError:
Err.Clear
Exists = False
End Function
这是不对的:您可以在字典中存储任何类型的对象/值“Items可以是任何形式的数据”当您只需要存储多个值/对象以及一个键,并检查字典中是否存在键时,一个简单的字典就足够了。如果要确保字典只包含特定类型的数据,必须将字典包装到对象中,并对其属性和方法进行个性化设置。这也可以通过集合对象和其他响应中给出的Exists()方法来完成。为了避免这个问题,最好省略赋值部分,也就是说,删除指令集o=col(index)或v=col(index)和变量声明,只写col.item index,这与对象和简单值的作用相同。