devxlogo

Check Whether a Given Key Exists in a Collection

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    Else        ItemExist = False    End IfEnd Function

size=3>
If Err.Number is 450, that means mCol(Key) returns an object not a generic data type. If a customized collection is created, it

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist