VB and VBA Users Source Code: Determine if an item exists in a collection
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
VB/VBA Source Code
Determine if an item exists in a collection
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Tuesday, October 09, 2001
Hits:
1709
Category:
Visual Basic General
Article:
The following code shows you how to determine if an item exists within a collection. Option Explicit 'Purpose : Determines if an item already exists in a collection 'Inputs : oCollection The collection to test for the existance of the item ' vIndex The index of the item. ' [vItem] See Outputs 'Outputs : Returns True if the item already exists in the collection. ' [vItem] The value of the item, if it exists, else returns "empty". 'Author : Andrew Baker 'Date : 28/Sep/2001 'Notes : 'Example : Function CollectionItemExists(vIndex As Variant, oCollection As Collection, Optional vItem As Variant) As Boolean On Error GoTo ErrNotExist 'Clear output result If IsObject(vItem) Then Set vItem = Nothing Else vItem = Empty End If If VarType(vIndex) = vbString Then 'Test if item exists If IsObject(oCollection.Item(CStr(vIndex)) Then 'Return an object Set vItem = oCollection.Item(CStr(vIndex)) Else 'Return an standard variable vItem = oCollection.Item(CStr(vIndex)) End If Else 'Test if item exists If IsObject(oCollection.Item(CStr(vIndex)) Then 'Return an object Set vItem = oCollection.Item(Int(vIndex)) Else 'Return an standard variable vItem = oCollection.Item(Int(vIndex)) End If End If 'Return success CollectionItemExists = True Exit Function ErrNotExist: CollectionItemExists = False On Error GoTo 0 End Function 'Demonstration routine Sub Test() Dim oColl As New Collection, oValue As Variant oColl.Add "ANDREW1", "KEYA" oColl.Add "ANDREW2", "KEYB" 'Return the two items in the collection Debug.Print CollectionItemExists("KEYA", oColl, oValue) Debug.Print "Returned: " & oValue Debug.Print "-----------" Debug.Print CollectionItemExists(2, oColl, oValue) Debug.Print "Returned: " & oValue 'Should fail Debug.Print CollectionItemExists("KEYC", oColl, oValue) Debug.Print "Returned: " & oValue Set oColl = Nothing End Sub
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder