VBA array sort function?

后端 未结 13 1990
北荒
北荒 2020-11-22 05:28

I\'m looking for a decent sort implementation for arrays in VBA. A Quicksort would be preferred. Or any other sort algorithm other than bubble or merge would suffice.

<
13条回答
  •  太阳男子
    2020-11-22 06:12

    @Prasand Kumar, here's a complete sort routine based on Prasand's concepts:

    Public Sub ArrayListSort(ByRef SortArray As Variant)
        '
        'Uses the sort capabilities of a System.Collections.ArrayList object to sort an array of values of any simple
        'data-type.
        '
        'AUTHOR: Peter Straton
        '
        'CREDIT: Derived from Prasand Kumar's post at: https://stackoverflow.com/questions/152319/vba-array-sort-function
        '
        '*************************************************************************************************************
    
        Static ArrayListObj As Object
        Dim i As Long
        Dim LBnd As Long
        Dim UBnd As Long
    
        LBnd = LBound(SortArray)
        UBnd = UBound(SortArray)
    
        'If necessary, create the ArrayList object, to be used to sort the specified array's values
    
        If ArrayListObj Is Nothing Then
            Set ArrayListObj = CreateObject("System.Collections.ArrayList")
        Else
            ArrayListObj.Clear  'Already allocated so just clear any old contents
        End If
    
        'Add the ArrayList elements from the array of values to be sorted. (There appears to be no way to do this
        'using a single assignment statement.)
    
        For i = LBnd To UBnd
            ArrayListObj.Add SortArray(i)
        Next i
    
        ArrayListObj.Sort   'Do the sort
    
        'Transfer the sorted ArrayList values back to the original array, which can be done with a single assignment
        'statement.  But the result is always zero-based so then, if necessary, adjust the resulting array to match
        'its original index base.
    
        SortArray = ArrayListObj.ToArray
        If LBnd <> 0 Then ReDim Preserve SortArray(LBnd To UBnd)
    End Sub
    

提交回复
热议问题