自行定义快速排序演算法 VBA 巨集函数,处理各种阵列排序问题。
在 Excel VBA 中并没有提供阵列排序的函数可用,如果想要对阵列的元素进行排序,可以自己定义一个快速排序演算法函数来处理。
另外对于数据量比较小的情况,也可以考虑简单的泡沫排序法,这个可以参考 VBA 泡沫排序教程。
快速排序 VBA 巨集函数
以下是一段根据速排序演算法所实作的排序函数:
' 快速排序函数 Public Sub QuickSort(vArray As Variant, inLow As Long, inHi As Long) Dim pivot As Variant Dim tmpSwap As Variant Dim tmpLow As Long Dim tmpHi As Long tmpLow = inLow tmpHi = inHi pivot = vArray((inLow + inHi) 2) While (tmpLow <= tmpHi) While (vArray(tmpLow) < pivot And tmpLow < inHi) tmpLow = tmpLow + 1 Wend While (pivot < vArray(tmpHi) And tmpHi > inLow) tmpHi = tmpHi - 1 Wend If (tmpLow <= tmpHi) Then tmpSwap = vArray(tmpLow) vArray(tmpLow) = vArray(tmpHi) vArray(tmpHi) = tmpSwap tmpLow = tmpLow + 1 tmpHi = tmpHi - 1 End If Wend If (inLow < tmpHi) Then QuickSort vArray, inLow, tmpHi If (tmpLow < inHi) Then QuickSort vArray, tmpLow, inHi End Sub
这个 QuickSort
函数的使用方式为:
QuickSort 阵列, 索引下限值, 索引上限值
最常见的用法是用 LBound
与 UBound
自动算出阵列索引的上下限, 传给 QuickSort
排序整个阵列:
QuickSort arr, LBound(arr), UBound(arr)
数值阵列排序
以下是一个单的排序数值应用范例:
Sub Test() ' 建立测试用阵列 Dim arr As Variant arr = Array(2, 5, 4, 1, 3) ' 对阵列进行排序 QuickSort arr, LBound(arr), UBound(arr) ' 输出结果 For i = LBound(arr) To UBound(arr) Debug.Print "元素 " & i & " = " & arr(i) Next i End Sub
在这段代码当中,当我们呼叫完 QuickSort
函数之后,arr
阵列中的元素就会变成排序好的状态,然后我们再用一个 For
循环配合 Debug.Print
输出阵列的内容,执行值记得要打开「及时运算窗口」(快速键为 Ctrl + g),这样才能看到输出的结果。
VBA 数值阵列排序
文字阵列排序
这一个 QuickSort
函数并没有限制阵列的数据型态,如果阵列的元素是文字,它就会依照字母顺序排序:
Sub Test() ' 建立测试用阵列 Dim arr As Variant arr = Array("Red", "Yellow", "Green", "Blue") ' 对阵列进行排序 QuickSort arr, LBound(arr), UBound(arr) ' 输出结果 For i = LBound(arr) To UBound(arr) Debug.Print "元素 " & i & " = " & arr(i) Next i End Sub
执行的结果如下:
VBA 文字阵列排序
参考数据:Stack Overflow