Test if a given value matches an element of the provided array


2012, Feb 01 edited
tags: VBA Array Array 



Function isInArray(el As Variant, v As Variant) As Boolean
'Desc: Check if element el is in input array v
'Copyright Realce.net 2012
On Error GoTo emng_isInArray
    Dim bRes As Boolean
    bRes = False
    Dim i As Integer
    If isArray(v) Then
        For i = LBound(v) To UBound(v)
            If (v(i) = el) Then
                bRes = True
                Exit For
            End If
        Next i
        isInArray = bRes
        Exit Function
    Else
    MsgBox "Error : Not an array ", vbOKOnly + vbExclamation, "Error isInArray function"
    Exit Function
    End If
emng_isInArray:
    MsgBox "Error : " + Err.Description, vbOKOnly + vbExclamation, "Error array_show function"
    Exit Function
End Function





Function allowing to sort in ascending or descending order the elements of the v array



Thanks to the invert array function, it's possible to enhance the sort function in order to allow not only ascending but also descending order.

To do so, we add a parameter, a flag fl_asc allowing to sort in ascending order in case it's set to True, in descending order if set to false. In this case we use the array_invert function before returning the resulting array to obtain the desired sorting(code lines 021-026).


Function array_sort(v, fl_asc)
'Desc: sort the elements of the input array v
'Copyright Realce.net 2012
On Error GoTo emng_array_sort
If isArray(v) Then
    Dim cnt As Boolean
    cnt = True
    If (UBound(v) > 1) Then
        Do While (cnt = True)
            cnt = False
            For i = LBound(v) To UBound(v) - 1
                If (v(i) > v(i + 1)) Then
                    tmp = v(i)
                    v(i) = v(i + 1)
                    v(i + 1) = tmp
                    cnt = True
                End If
            Next i
        Loop
    End If
    If (fl_asc = True) Then
        array_sort = v
    Else
        array_sort = array_invert(v)
    End If
Exit Function
Else
    MsgBox "Error : Not an array ", vbOKOnly + vbExclamation, "Error array_sort function"
    Exit Function
End If
emng_array_sort:
    MsgBox "Error : " + Err.Description, vbOKOnly + vbExclamation, "Error array_sort function"
    Exit Function
End Function



Test code n°1 :

	
Sub test_array_sort()
    Dim e As Variant
    e = Array(3, 6, 7, 4, 4, 1, 2)
    MsgBox array_show(array_sort(e, True))
End Sub

The above code will produce the display of a message box containing the following text :
	
Array(1,2,3,4,4,6,7)

Test code n°2 :


Sub test_array_sort()
    Dim e As Variant
    e = Array(3, 6, 7, 4, 4, 1, 2)
    MsgBox array_show(array_sort(e, False))
End Sub

The above code will produce the display of a message box containing the following text :

Array(7,6,4,4,3,2,1)

The fuel of coding inspiration:music, travel, photography and whatever drives creativity to code.

You might also like