Visual Basic Programming Code Examples Visual Basic > Other Code Examples Determine if an item exists in a collection Determine if an item exists in a collection 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". '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 VarType(oCollection.Item(CStr(vIndex))) = vbObject 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 VarType(oCollection.Item(Int(vIndex))) = vbObject 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 "red1", "KEYA" oColl.Add "red2", "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