Visual Basic 6 function "sort"

Go back

Below you'll find the source for the Visual Basic 6 function sort.

Attribute VB_Name = "modSort"
' This function is downloaded from:
' http://www.stefanthoolen.nl/archive/vb6-functions/
' 
' You may freely distribute this file but please leave all comments, including this one, in it.
' 
' @Author Stefan Thoolen <mail@stefanthoolen.nl>

Option Explicit

Public Enum eSortFlags
    SORT_REGULAR = 0
    SORT_NUMERIC = 1
    SORT_STRING = 2
End Enum

''
' Sort an array
' See also: http://www.php.net/manual/en/function.sort.php
' @param    array       arr     The input array
' @param    eSortFlags          The optional second parameter sort_flags may be used to modify the sorting behavior
' @return   boolean             Returns TRUE on success or FALSE on failure
' @author   Stefan Thoolen <mail@stefanthoolen.nl>
Public Function sort(ByRef arr As Variant, Optional ByVal sort_flags As eSortFlags = SORT_REGULAR) As Boolean
    On Error GoTo sort_error
    If LBound(arr) = UBound(arr) Then Exit Function
    On Error GoTo 0
    
    Dim i As Integer, tmp As Variant, changes_made As Boolean, move As Boolean
    
    Do
        changes_made = False
        For i = LBound(arr) To UBound(arr) - 1
            move = False
            ' Tried this in one If-statement but it gave type errors
            ' when converting a string value to numeric, even when I was using SORT_STRING
            If sort_flags = SORT_REGULAR Then If arr(i) > arr(i + 1) Then move = True
            If sort_flags = SORT_NUMERIC Then If CDbl(arr(i)) > CDbl(arr(i + 1)) Then move = True
            If sort_flags = SORT_STRING Then If CStr(arr(i)) > CStr(arr(i + 1)) Then move = True
            If move Then
                tmp = arr(i + 1)
                arr(i + 1) = arr(i)
                arr(i) = tmp
                changes_made = True
            End If
        Next i
    Loop While changes_made
    
    sort = True
sort_error:
End Function