Thread: collection obj
View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.programming
Peter T Peter T is offline
external usenet poster
 
Posts: 5,600
Default collection obj

The thing to keep in mind with collections is they can store multiple
similar items or values but keys are always unique. So be sure to include
the optional key, eg

Sub test()
Dim n As Long
Dim col As Collection
Set Col = New collection

col.Add "abc", "abc"
n = 123
col.Add n, CStr(n)

Debug.Print ItemExists(col, "abc") ' true
Debug.Print ItemExists(col, "xyz") ' false

End Sub

Function ItemExists(col As Collection, sKey As String) As Boolean
Dim v As Variant
On Error GoTo errExit
v = col(sKey)
ItemExists = True
Exit Function
errExit:

End Function

I see you have discovered the Dictionary object which indeed adds a lot of
functionality. However if the only purpose is to test if items exist I'd
stick with the Collection.

Regards,
Peter T


"cate" wrote in message
...
I'm having some trouble with the collection obj. My first time out.
I seem can't test it.
(placing strings into what I would call a hash/dictionary. Am I doing
that?)

Dim usedFields As Collection
Set usedFields = New Collection

usedFields.Add("string); ' doesn't die

Later, I want to know if an item exists

if usedFields.Item("string")
if exists.usedFields ...
if usedFields.Item("string") < ""
if usedFields.Item("string") < 0

All get me the yellow bug line. How do test for exists?

Help. Thank you.