excelvbaexcel-2019

Get the reverse index of a value from Array in VBA


I have an integer array.

Dim a as Variant
a = Array(1,2,3,4,1,2,3,4,5)
Dim index as Integer
index = Application.Match(4,a,0) '3

index is 3 here. It returns the index of first occurrence of 4. But I want the last occurrence index of 4.

In python, there is rindex which returns the reverse index. I am new to vba, any similar api available in VBA? Note: I am using Microsoft office Professional 2019 Thanks in advance.


Solution

  • XMATCH() avaibalble in O365 and Excel 2021. Try-

    Sub ReverseMatch()
    Dim a As Variant
    Dim index As Integer
    
        a = Array(1, 2, 3, 4, 1, 2, 3, 4, 5)
        index = Application.XMatch(4, a, 0, -1) '-1 indicate search last to first.
        Debug.Print index
    
    End Sub
    

    You can also try below sub.

    Sub ReverseMatch()
    Dim a As Variant
    Dim index As Integer, i As Integer
    
        a = Array(1, 2, 3, 4, 1, 2, 3, 4, 5)
    
        For i = UBound(a) To LBound(a) Step -1
            If a(i) = 4 Then
                Debug.Print i + 1
                Exit For
            End If
        Next i
    
    End Sub