UtterAccess HomeUtterAccess Wiki

Welcome Guest ( Log In | Register )

Custom Search
Edit Discussion
> Array Sort in VBA    
Array Sort in VBA

Array Sort in VBA

The Array Sort works on bringing element into a temporary array one by one and comparing the incoming element with the already-populated elements and assigning an index.

The index is used to reorder the records.

A spreadsheet demonstrating the use of the array sort is attached.


Option Explicit
Option Base 1

Sub SortArray(AV() As Variant)
Dim AR() As Long    ' Array containing record number
Dim AI() As Long    ' Array containing the index for the record
Dim AT() As Variant ' Temporary Array
Dim k1 As Long, k2 As Long
Dim cl As Range
Dim Nelements As Long

' Initialize Variables
Nelements = UBound(AV)
ReDim AR(Nelements)
ReDim AI(Nelements)
ReDim AT(Nelements)

' Create the index
For k1 = 1 To Nelements
   AR(k1) = k1
   AI(k1) = 0
   For k2 = 1 To k1
       If AV(k2) > AV(k1) Then
           AI(k2) = AI(k2) + 1
           AI(k1) = AI(k1) + 1
       End If
   Next k2
Next k1

' Do the actual sort and assign it to the temp array
For k1 = 1 To Nelements
   For k2 = 1 To Nelements
       If k1 = AI(k2) Then
           AT(k1) = AV(AR(k2))
           Exit For
       End If
   Next k2
Next k1

' Set the orginal array to the sorted temp array

End Sub

media: Array_Sort.zip

Edit Discussion
Custom Search

Thank you for your support!
This page has been accessed 3,151 times.  This page was last modified 22:27, 24 January 2014 by dflak.   Disclaimers