Collection

  • Thread starter Thread starter Todd Huttenstine
  • Start date Start date
T

Todd Huttenstine

Hey

How do you test to see if a particular value is in a
collection object?

For example, I have a collection with 5 items in it. The
items in it are: "abc", "def", "ghi", "jkl", and "mno".
How can I test to see if the value "jkl" is in this
collection, and return true or false?


Thanks
Todd
 
Function CollectionContains(TxtValue as String) as Boolean
Dim MyObject as Object
CollectionContains = False
For each MyObject in ObjectName.CollectionName ' You need to put the actual
object and collection name in the code here
If MyObject.Value = TxtValue Then CollectionContains = True
Next MyObject
End Function
 
Todd said:
Hey

How do you test to see if a particular value is in a
collection object?

For example, I have a collection with 5 items in it. The
items in it are: "abc", "def", "ghi", "jkl", and "mno".
How can I test to see if the value "jkl" is in this
collection, and return true or false?


Thanks
Todd

If you check the reference to Microsoft Scripting Runtime in the VB
Editor, you can use a Dictionary Object instead of a Collection and it
gets easy.

Dim dict As New Dictionary
Dim arr, Elem
arr = Array("abc", "def", "ghi", "jkl", "mno")
For Each Elem In arr
dict.Add CStr(Elem), Elem
Next
Debug.Print dict.Exists("jkl") '<--returns True
Debug.Print dict.Exists("xyz") '<--returns False

Alan Beban
 
I should have mentioned that this assumes that the elements in the array
are unique.

Alan Beban
 
Todd,

Here is a function to test it

Public Function IfExists(col As Collection, ByVal sKey As String)

On Error GoTo NoSuchKey

If VarType(col.Item(sKey)) = vbObject Then
' force an error condition if key does not exist
End If

IfExists = True

Exit Function

NoSuchKey:
IfExists = False

End Function





--

HTH

RP
(remove nothere from the email address if mailing direct)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top