Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Intermediate
Feb 2, 2001



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Check Whether a Given Key Exists in a Collection

It is unfortunate that VB5 does not provide a quick way to check if an item with a certain key exists in a collection. This results in errors if an item with an existing key is added or access is attempted with a key not existing in the collection. Typically, the On Error statement is used to trap such an error. But when working with many collections, this becomes tedious and unattractive.

This function checks to see if a given key exists in a collection.
Public Function ItemExist(mCol As Collection, Key As String) As Boolean
    Dim V as Variant
    On Error Resume Next
    V = mCol(Key)
    If Err.Number = 450 Or Err.Number = 0 Then
        ItemExist = True
        ItemExist = False
    End If
End Function

If Err.Number is 450, that means mCol(Key) returns an object not a generic data type. If a customized collection is created, it
Guoran Xie
Thanks for your registration, follow us on our social networks to keep up-to-date