在Excel中没有提供直接的方法或函数用于数组排序,因此若要使用VBA进行数组排序,则需要采用我们在数据结构与算法课程中学到的排序算法。
这里转载了Using a Visual Basic Macro to Sort Arrays in Microsoft Excel中给出的使用VBA进行数组排序的两种方法,分别采用的排序算法为:选择排序和冒泡排序。
Method 1: Selection Sort
Function SelectionSort(TempArray As Variant)
Dim MaxVal As Variant
Dim MaxIndex As Integer
Dim i, j As Integer
' Step through the elements in the array starting with the
' last element in the array.
For i = UBound(TempArray) To 1 Step -1
' Set MaxVal to the element in the array and save the
' index of this element as MaxIndex.
MaxVal = TempArray(i)
MaxIndex = i