I have a collection with several elements in VBA, each of these elements has a key assigned.
I would like to know the position of a given element in the collection u
Essentially, no. There's not a faster way. Not using a collection at least. Here's the fastest way I know to find the index of an item in a collection.
' returns index of item if found, returns 0 if not found
Public Function IndexOf(ByVal coll As Collection, ByVal item As Variant) As Long
Dim i As Long
For i = 1 To coll.Count
If coll(i) = item Then
IndexOf = i
Exit Function
End If
Next
End Function
Note that we exit the function as soon as we've found the first matching item. This algorithm has an average and worst case of O(n) where n is the number of items in the collection.
I think there may be another reason you want to be able to find the index though, so I'm going to suggest also taking a look at the Scripting.Dictionary in the Microsoft Scripting Runtime library. While, there is also no way to get an item's index via it's key value (other than looping), you can actually retrieve the key values from the dictionary, not just it's items. I suspect that you may be asking this question because of the lack of this ability in the built in Collection
object.