Visual Basic Programming: How to check element exists in Collection

One of the missing function code that made by the VB Class Builder while making a Collection Class is CheckExists function to check whether the key associated to an object in the collection is already exists or not.

Collections in Visual Basic

In general, a collection is an object used for grouping and managing related objects. Check out Microsoft article about Collections in Visual Basic

Creating Collection Class using VB Class Builder

The simplest way to create collection class is by using the VB Class Builder. Here's the simple step:
  • Right click on the Project Explorer area
  • Select Add > Class Module
  • Select VB Class Builder, and click Open
  • Select File > New > Collection and Set your class to be grouped it the Collection Class, Set The collection Name and click OK
  • Update Project and Close the Builder

Notice, you will have one new class based on the name you set on the Builder. Open the code window for the New Collection Class and you will notice there is no CheckExists function to check whether the key associated to an object it the collection is already exists or not.

Here is my function code to check if an object exists in a collection object
Public Function CheckExists(vntIndexKey As Variant) As Boolean
On Error Resume Next
Dim cObj As Object

' just get the object
Set cObj = mCol(vntIndexKey)

' here's the key! Trap the Error Code
' when the error code is 5 then the Object is Not Exists
CheckExists = (Err <> 5)

' just to clear the error
If Err <> 0 Then Call Err.Clear
Set cObj = Nothing
End Function

You can simply copy this code and paste it in the Collection class and now you have the CheckExists function in your collection Class. Good Luck!

Comments

Popular posts from this blog

How to Create Hyperlink on Blogger Post

How to Add a Sudo User on AlmaLinux 9.2 (Turquoise Kodkod): A Step-by-Step Guide

How to Show and Hide Text in Blog Post