How to add unique items in a collection
Posted on September 6, 2010
There are instances where you will be having sevaral items and you only need to add unique items into a collection. Here is one of the way I can think of in VB6:
Instructions:
- Create a new Project
- Add a new module to it and name it as module1
Let's say you have sevaral items as shown below to a collection col:
John
Joseph
Jawahar
Rahim
Rahul
Raghu
Rao
Joseph
Rahim
John
Andrew
Steve
Jawahar
As you can see some of the items are duplicates. We only want to add unique items to the collection.
Copy the following code to module1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | Option Explicit Private Sub Main() Dim col As New Collection Dim sItem As String Dim oVar As Variant Call AddUniqueItemsToCollection(col, "John") Call AddUniqueItemsToCollection(col, "Joseph") Call AddUniqueItemsToCollection(col, "Jawahar") Call AddUniqueItemsToCollection(col, "Rahim") Call AddUniqueItemsToCollection(col, "Rahul") Call AddUniqueItemsToCollection(col, "Raghu") Call AddUniqueItemsToCollection(col, "Rao") Call AddUniqueItemsToCollection(col, "Joseph") Call AddUniqueItemsToCollection(col, "Rahim") Call AddUniqueItemsToCollection(col, "John") Call AddUniqueItemsToCollection(col, "Andrew") Call AddUniqueItemsToCollection(col, "Steve") Call AddUniqueItemsToCollection(col, "Jawahar") For Each oVar In col Debug.Print oVar Next oVar 'As you can see all duplicate items are removed from the colection End Sub Private Sub AddUniqueItemsToCollection(ByRef col As Collection, ByVal sItem As String) On Error GoTo AddUniqueItemsToCollection_Error col.Add sItem, sItem On Error GoTo 0 Exit Sub AddUniqueItemsToCollection_Error: If Err.Number = 457 Then 'the item already exist Exit Sub Else MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure AddUniqueItemsToCollection of Module Module1" End If End Sub |
If you know any other method(s) of adding unique items in a collection or have any other comments or questions, please post as a comment.
Thank you :)