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

后端 未结 4 842
一整个雨季
一整个雨季 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:32

    I recently had the same "issue" and used this workaround:

    Create two collections: one containing the actual strings of interest and one containing numbers from 1 to n with the actuals strings as keys. This way you can retrieve the index since it's a value in the second collection.

    Sub example()
    
        'imagine we are reading out following excel column
    
        'one
        'two
        'three
    
        Dim textcol, numcol As New Collection
        Dim i, index As Integer
        Dim str As String
    
        For i = 1 To Range.Rows.Count
            textcol.Add Range.Cells(i, 1)       'value, no key
            numcol.Add i, Range.Cells(i, 1)     'i, value as key
        Next i
    
        'textcol: "one", "two", "three"
        'numcol: 1 ["one"], 2 ["two"], 3 ["three"]
    
        str = "two"
        index = numcol(str) '~> 2
    
    End Sub
    

    It's not pretty but it worked for me.

提交回复
热议问题