Determining Whether An Object Is A Member of A Collection in VBA - Stack Overflow
Determining Whether An Object Is A Member of A Collection in VBA - Stack Overflow
63 Specifically, I need to find out whether a table definition is a member of the TableDefs
collection.
Your best bet is to iterate over the members of the collection and see if any match what you
are looking for. Trust me I have had to do this many times.
25
The second solution (which is much worse) is to catch the "Item not in collection" error and
then set a flag to say the item does not exist.
12 is this really the only way to do it? – inglesp Sep 26 '08 at 5:03
6 "correct" perhaps, but still very unsatisfactory. Thanks both. – inglesp Sep 26 '08 at 5:20
3 A VB6/VBA collection is not just something you can iterate over. It also provides optional key access. –
Joe Sep 26 '08 at 18:27
4 Solution provided by Mark Nold below is far superior – Mr1159pm Feb 3 '13 at 6:19
https://stackoverflow.com/questions/137845/determining-whether-an-object-is-a-member-of-a-collection-in-vba 1/10
10/8/2020 Determining whether an object is a member of a collection in VBA - Stack Overflow
Contains = False
End Function
1 This seems like the simplest of all solutions presented here. I've used this and it works perfectly. I did
however have to change the col argument to be of type Variant. – A. Murray Dec 9 '12 at 21:55
1 Nearly 6 years later, it is still a perfectly viable solution. I'm using it as is with no issues. – FreeMan Apr
7 '15 at 15:01
3 It is a great solution, it is just a bit silly that thousands of people have to reimplement it. VB/VBA are
supposed to be higher level than that. – Leo May 4 '15 at 0:34
23 This doesn't work if the value for a key is an object not a primitive - if the value is an object you'll get an
assignment error (object references need to be assigned with "Set"), thus returning "False" even if the
key exists. Replace the line obj = col(key) with IsObject(col(key)) to handle both object and primitive
values. – Richard H May 17 '16 at 8:34
Not exactly elegant, but the best (and quickest) solution i could find was using OnError. This
will be significantly faster than iteration for any medium to large collection.
39
Public Function InCollection(col As Collection, key As String) As Boolean
Dim var As Variant
Dim errNumber As Long
InCollection = False
Set var = Nothing
Err.Clear
On Error Resume Next
var = col.Item(key)
errNumber = CLng(Err.Number)
On Error GoTo 0
End Function
9 I don't perceive this as non elegant... it's a try-catch approach, something very normal in C++ and java,
e.g. I'd bet it's much more fast that iterating the whole collection, because VB calculated the hash for
the provided key, and searched it on the hash table, not in the item's collection. – jpinto3912 Nov 12 '08
at 19:17
3 this implementation is not okay: i.e. it will return True if any other error than #5 occurs – TmTron Apr 22
https://stackoverflow.com/questions/137845/determining-whether-an-object-is-a-member-of-a-collection-in-vba 2/10
10/8/2020 Determining whether an object is a member of a collection in VBA - Stack Overflow
'13 at 15:55
3 errNumber is not 5 here, it's 3265 instead :( ... It's not elegant from this aspect - of relying on hard-
coded error codes – Amir Gonnen May 26 '14 at 7:20
This is an old question. I have carefully reviewed all the answers and comments, tested the
solutions for performance.
12
I came up with the fastest option for my environment which does not fail when a collection has
objects as well as primitives.
In addition, this solution does not depend on hard-coded error values. So the parameter col
As Collection can be substituted by some other collection type variable, and the function must
still work. E.g., on my current project, I will have it as col As ListColumns .
1 Excellent solution, and concise. Thank you! – Andre Feb 9 '18 at 10:54
@user2426679 Thank you! I love slight improvements which reduce the amount of code :) – ZygD Sep
30 '18 at 8:45
I created this solution from the above suggestions mixed with microsofts solution of for
iterating through a collection.
3
Public Function InCollection(col As Collection, Optional vItem, Optional vKey) As
Boolean
On Error Resume Next
InCollection = False
https://stackoverflow.com/questions/137845/determining-whether-an-object-is-a-member-of-a-collection-in-vba 3/10
10/8/2020 Determining whether an object is a member of a collection in VBA - Stack Overflow
For Each vColItem In col
If vColItem = vItem Then
InCollection = True
GoTo Exit_Proc
End If
Next vColItem
End If
Exit_Proc:
Exit Function
Err_Handle:
Resume Exit_Proc
End Function
You can shorten the suggested code for this as well as generalize for unexpected errors. Here
you go:
3
Public Function InCollection(col As Collection, key As String) As Boolean
incol:
InCollection = (Err.Number = 0)
End Function
In your specific case (TableDefs) iterating over the collection and checking the Name is a
good approach. This is OK because the key for the collection (Name) is a property of the
2 class in the collection.
But in the general case of VBA collections, the key will not necessarily be part of the object in
the collection (e.g. you could be using a Collection as a dictionary, with a key that has nothing
to do with the object in the collection). In this case, you have no choice but to try accessing
the item and catching the error.
2
https://stackoverflow.com/questions/137845/determining-whether-an-object-is-a-member-of-a-collection-in-vba 4/10
10/8/2020 Determining whether an object is a member of a collection in VBA - Stack Overflow
err:
Contains = False
End Function
this version works for primitive types and for classes (short test-method included)
lErrNumber = 0
sErrDescription = "unknown error occurred"
Err.Clear
On Error Resume Next
' note: just access the item - no need to assign it to a dummy value
' and this would not be so easy, because we would need different
' code depending on the type of object
' e.g.
' Dim vItem as Variant
' If VarType(oCollection.Item(sKey)) = vbObject Then
' Set vItem = oCollection.Item(sKey)
' Else
' vItem = oCollection.Item(sKey)
' End If
oCollection.Item sKey
lErrNumber = CLng(Err.Number)
sErrDescription = Err.Description
On Error GoTo 0
https://stackoverflow.com/questions/137845/determining-whether-an-object-is-a-member-of-a-collection-in-vba 5/10
10/8/2020 Determining whether an object is a member of a collection in VBA - Stack Overflow
Dim asTest As New Collection
Contains = False
For Each item In col
If item = thisItem Then
Contains = True
Exit Function
End If
Next
End Function
Please edit with more information. Code-only and "try this" answers are discouraged, because they
contain no searchable content, and don't explain why someone should "try this". – abarisone Sep 13
'16 at 9:47
1 This is a disastrous solution in terms of speed, the ON ERROR solution is much better: see low-
bandwidth.blogspot.com.au/2013/12/… – Ben McIntyre Feb 16 '18 at 7:36
1 The solution is the best, when the collection contains no keys only items, since the ON ERROR
solution will not work in this case. What explanation is needed for this simple solution? A loop over the
members of the collection and check for equality. – Dietrich Baumgarten Feb 10 at 14:00
It requires some additional adjustments in case the items in the collection are not Objects, but
Arrays. Other than that it worked fine for me.
1
https://stackoverflow.com/questions/137845/determining-whether-an-object-is-a-member-of-a-collection-in-vba 6/10
10/8/2020 Determining whether an object is a member of a collection in VBA - Stack Overflow
Source: http://coderstalk.blogspot.com/2007/09/visual-basic-programming-how-to-check.html
i used this code to convert array to collection and back to array to remove duplicates,
assembled from various posts here (sorry for not giving properly credit).
0
Function ArrayRemoveDups(MyArray As Variant) As Variant
Dim nFirst As Long, nLast As Long, i As Long
Dim item As Variant, outputArray() As Variant
Dim Coll As New Collection
Not my code, but I think it's pretty nicely written. It allows to check by the key as well as by the
Object element itself and handles both the On Error method and iterating through all
https://stackoverflow.com/questions/137845/determining-whether-an-object-is-a-member-of-a-collection-in-vba 7/10
10/8/2020 Determining whether an object is a member of a collection in VBA - Stack Overflow
0 Collection elements.
https://danwagner.co/how-to-check-if-a-collection-contains-an-object/
I'll not copy the full explanation since it is available on the linked page. Solution itself copied in
case the page eventually becomes unavailable in the future.
The doubt I have about the code is the overusage of GoTo in the first If block but that's easy to
fix for anyone so I'm leaving the original code as it is.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'INPUT : Kollection, the collection we would like to examine
' : (Optional) Key, the Key we want to find in the collection
' : (Optional) Item, the Item we want to find in the collection
'OUTPUT : True if Key or Item is found, False if not
'SPECIAL CASE: If both Key and Item are missing, return False
Option Explicit
Public Function CollectionContains(Kollection As Collection, Optional Key As Variant,
Optional Item As Variant) As Boolean
Dim strKey As String
Dim var As Variant
strKey = CStr(Key)
CheckForObject:
If IsObject(Kollection(strKey)) Then
CollectionContains = True
On Error GoTo 0
Exit Function
End If
NotFound:
CollectionContains = False
On Error GoTo 0
Exit Function
'If the Item was provided but the Key was not, then...
ElseIf Not IsMissing(Item) Then
CollectionContains = False '<~ assume that we will not find the item
'We have to loop through the collection and check each item against the passed-
in Item
For Each var In Kollection
If var = Item Then
CollectionContains = True
Exit Function
End If
Next var
https://stackoverflow.com/questions/137845/determining-whether-an-object-is-a-member-of-a-collection-in-vba 8/10
10/8/2020 Determining whether an object is a member of a collection in VBA - Stack Overflow
End If
End Function
I did it like this, a variation on Vadims code but to me a bit more readable:
Dim i As Integer
For i = 1 To col.Count
Next i
Contains = False
End Function
https://stackoverflow.com/questions/137845/determining-whether-an-object-is-a-member-of-a-collection-in-vba 9/10
10/8/2020 Determining whether an object is a member of a collection in VBA - Stack Overflow
https://stackoverflow.com/questions/137845/determining-whether-an-object-is-a-member-of-a-collection-in-vba 10/10