Return Index of an Element in an Array Excel VBA

后端 未结 7 1657
悲&欢浪女
悲&欢浪女 2020-11-29 20:42

I have an array prLst that is a list of integers. The integers are not sorted, because their position in the array represents a particular column on a spreadsheet. I want t

7条回答
  •  情话喂你
    2020-11-29 20:56

    Taking care of whether the array starts at zero or one. Also, when position 0 or 1 is returned by the function, making sure that the same is not confused as True or False returned by the function.

    Function array_return_index(arr As Variant, val As Variant, Optional array_start_at_zero As Boolean = True) As Variant
    
    Dim pos
    pos = Application.Match(val, arr, False)
    
    If Not IsError(pos) Then
        If array_start_at_zero = True Then
            pos = pos - 1
            'initializing array at 0
        End If
       array_return_index = pos
    Else
       array_return_index = False
    End If
    
    End Function
    
    Sub array_return_index_test()
    Dim pos, arr, val
    
    arr = Array(1, 2, 4, 5)
    val = 1
    
    'When array starts at zero
    pos = array_return_index(arr, val)
    If IsNumeric(pos) Then
    MsgBox "Array starting at 0; Value found at : " & pos
    Else
    MsgBox "Not found"
    End If
    
    'When array starts at one
    pos = array_return_index(arr, val, False)
    If IsNumeric(pos) Then
    MsgBox "Array starting at 1; Value found at : " & pos
    Else
    MsgBox "Not found"
    End If
    
    
    
    End Sub
    

提交回复
热议问题