VBA 內建無陣列排序方法,需自行實作。本文提供氣泡排序法(升冪/降冪)與快速排序法(支援中文字串)完整 Function 程式碼。
Function UP(x() As Variant) As Variant()
Dim i As Long, j As Long, tmp As Variant
Dim d() As Variant
ReDim d(LBound(x) To UBound(x))
d = x
If LBound(x) = UBound(x) Then
UP = d
Exit Function
End If
For i = LBound(x) To UBound(x) - 1
For j = i + 1 To UBound(x)
If d(j) < d(i) Then
tmp = d(j): d(j) = d(i): d(i) = tmp
End If
Next j
Next i
UP = d
End Function
Function Down(x() As Variant) As Variant()
Dim i As Long, j As Long, tmp As Variant
Dim d() As Variant
ReDim d(LBound(x) To UBound(x))
d = x
If LBound(x) = UBound(x) Then
Down = d
Exit Function
End If
For i = LBound(x) To UBound(x) - 1
For j = i + 1 To UBound(x)
If d(j) > d(i) Then
tmp = d(j): d(j) = d(i): d(i) = tmp
End If
Next j
Next i
Down = d
End Function
Sub QuickSort2(MyArray() As Variant, L As Long, R As Long)
Dim I As Long, J As Long
Dim X As Variant, Y As Variant
Dim tp As Integer: tp = 1 ' 1=vbBinaryCompare, 0=vbTextCompare
I = L: J = R
X = MyArray((L + R) \ 2)
Do While I <= J
Do While StrComp(MyArray(I), X, tp) < 0 And I < R: I = I + 1: Loop
Do While StrComp(X, MyArray(J), tp) < 0 And J > L: J = J - 1: Loop
If I <= J Then
Y = MyArray(I)
MyArray(I) = MyArray(J)
MyArray(J) = Y
I = I + 1
J = J - 1
End If
Loop
If L < J Then QuickSort2 MyArray, L, J
If I < R Then QuickSort2 MyArray, I, R
End Sub
' 使用範例
Sub TestQuickSort()
Dim arr() As Variant
arr = Array("大", "眾", "計", "算", "機", "學", "習", "網")
QuickSort2 arr, 0, UBound(arr)
Dim s As String, k As Long
For k = LBound(arr) To UBound(arr)
s = s & arr(k) & " | "
Next
MsgBox s ' 顯示排序結果
End Sub
| 演算法 | 時間複雜度 | 適用資料量 | 中文支援 |
|---|---|---|---|
| 氣泡排序 | O(n²) | < 1,000 筆 | 需自行處理 StrComp |
| 快速排序 | O(n log n) 平均 | > 1,000 筆 | 內建 StrComp 正確比較中文 |
| Excel 工作表排序 | 高度優化 | 任何量級 | 最佳 |
Range.Sort 或 WorksheetFunction.Sort (Excel 365)。StrComp(..., vbTextCompare)(tp=0)依語言規則排序,而非位元組碼。