Instantly share code, notes, and snippets.

Embed
What would you like to do?
This short script tests a variety of Collections (using the Contains function)
Public Sub TestContains()
'Test "primitives" collection (i.e. Strings, Longs, etc.)
Dim colStrings As Collection
Set colStrings = New Collection
'Add Item / Key pairs (of strings)
colStrings.Add Item:="Item1", Key:="Key1"
colStrings.Add Item:="Item2", Key:="Key2"
'Verify that the Contains function works
Debug.Print "=== Testing Strings"
Debug.Print Contains(colStrings, "Key1") '<~ should print True
Debug.Print Contains(colStrings, "Key99") '<~ should print False
Debug.Print Contains(colStrings, "Key2") '<~ should print True
Debug.Print "=== Done Testing Strings!"
'Test "objects" collection (i.e. Ranges, Worksheets, etc.)
Dim colRanges As Collection
Set colRanges = New Collection
'Add Item / Key pairs (range / string)
colRanges.Add Item:=Range("A1"), Key:="RangeKey1"
colRanges.Add Item:=Range("A2"), Key:="RangeKey2"
'Verify that the Contains function works
Debug.Print "=== Testing Ranges"
Debug.Print Contains(colRanges, "RangeKey1") '<~ should print True
Debug.Print Contains(colRanges, "RangeKey3000") '<~ should print False
Debug.Print Contains(colRanges, "RangeKey2") '<~ should print True
Debug.Print "=== Done Testing Ranges!"
'Test "empty" collection (i.e. no items or keys)
Dim colEmpty As Collection
Set colEmpty = New Collection
'Verify that the Contains function works
Debug.Print "=== Testing Empty"
Debug.Print Contains(colEmpty, "AnyOldKey") '<~ should print False
Debug.Print "=== Done Testing Empty!"
'Test "nothing" collection (i.e. a nasty case haha)
Dim colNothing As Collection
Set colNothing = Nothing
'Verify that the Contains function works
Debug.Print "=== Testing Nothing"
Debug.Print Contains(colEmpty, "NothingKey") '<~ should print False
Debug.Print "=== Done Testing Nothing!"
'Test "long" collection where no key is provided
Dim colLongs As Collection
Set colLongs = New Collection
'Add Items
colLongs.Add Item:=1
colLongs.Add Item:=2
'Verify that the Contains function works
Debug.Print "=== Testing Longs (with no Keys)"
Debug.Print Contains(colLongs, , 1) '<~ should print True
Debug.Print Contains(colLongs, , 42) '<~ should print False
Debug.Print Contains(colLongs, , 2) '<~ should print True
Debug.Print "=== Done Testing Longs (with no Keys)!"
'Test "nothing passed in" collection, where no Key or Item is passed-in
Dim colNothingPassedIn As Collection
Set colNothingPassedIn = New Collection
'Add Items
colNothingPassedIn.Add Item:="Test", Key:="Test"
'Verify that the Contains function works
Debug.Print "=== Testing Nothing Passed In"
Debug.Print Contains(colNothingPassedIn) '<~ should print False
Debug.Print "=== Done Testing Nothing Passed In!"
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment