Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 446
  • Last Modified:

If a key exists in a Collection

Hi everyone,

The VB Collection object allows the user to add an item and a key associated with it (like a HashTable). How can I check if a key already exists in a collection object before I add another object to the collection? If I try to add a key that already exists, I would get a run time error.

Thanks!
xargon
0
xargon_123
Asked:
xargon_123
1 Solution
 
R_RajeshCommented:
Hi xargon_123,

add an error handler.

On Error Resume Next
MyCollection.Add 1, CStr(n)
On Error GoTo 0

to check if a key exists, i guess you will have to loop through all the items and check each key...



Rajesh
0
 
PSSUserCommented:
To check if a key exists, simply try to return the oject with that key. If it doesn't exist, you will receive a run time error 5 - Invalid procedure call or arguement:

On Error Resume Next
  MyCollection.Item(strKey)

  if Err.Number=5 then
   'Key doesn't exist
  else
   'Key exists
  end if
On Error GoTo 0
0
 
ShauliCommented:
You can do it while you add, as in:

Private Sub Command1_Click()
Dim myCollection As Collection, addItem As String, addKey As String
Set myCollection = New Collection
addItem = "xargon_123"
addKey = "Key_123"

On Error GoTo errorhandling
myCollection.Add addItem, addKey
myCollection.Add addItem, addKey

Set myCollection = Nothing
Exit Sub
errorhandling:
If Err.Number = 457 Then
    MsgBox "Key '" & addKey & "' already exist"
    Err.Clear
    Resume Next
End If
End Sub

S
0
 
RainUKCommented:
Alternatively you can use the Dictionary Object of the Windows Scripting Runtime instead of VBs collection object, similar to a collection but a lot more friendly. Also has a builtin method to check if a key exits e.g.

Dim doCol As Dictionary

    Set doCol = New Dictionary
   
    doCol.Add "Key1", "Item1"
    doCol.Add "Key2", "Item2"
    doCol.Add "Key3", "Item3"

    If doCol.Exists("Key2") = True Then
       
        ' Do something
   
    Else
       
        ' Do something else
   
    End If
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now