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).
' ***************************************************
' Procedure : array_sort
' Description : Inverts the order of the elements of the input array v
' Parameters 2
' v : the array
' fl_asc :ascending True/False
'
' Copyright Realce.net 2012 version:0.01
' ***************************************************
Function array_sort(v, fl_asc)
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)