Retrieve the index of an object stored in a collection using its key (VBA)

后端 未结 4 835
一整个雨季
一整个雨季 2020-12-11 11:01

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

4条回答
  •  执笔经年
    2020-12-11 11:30

    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.

提交回复
热议问题