任何排序算法都可以 - 您需要做的就是根据您的自定义标准进行项目比较:
Private Function SortCompare(one As String, two As String) As Boolean
Select Case True
Case Len(one) < Len(two)
SortCompare = True
Case Len(one) > Len(two)
SortCompare = False
Case Len(one) = Len(two)
SortCompare = LCase$(one) < LCase$(two)
End Select
End Function
例如,使用快速排序:
Public Sub CustomQuickSort(list() As String, first As Long, last As Long)
Dim pivot As String
Dim low As Long
Dim high As Long
low = first
high = last
pivot = list((first + last) \ 2)
Do While low <= high
Do While low < last And SortCompare(list(low), pivot)
low = low + 1
Loop
Do While high > first And SortCompare(pivot, list(high))
high = high - 1
Loop
If low <= high Then
Dim swap As String
swap = list(low)
list(low) = list(high)
list(high) = swap
low = low + 1
high = high - 1
End If
Loop
If (first < high) Then CustomQuickSort list, first, high
If (low < last) Then CustomQuickSort list, low, last
End Sub
使用示例:
Public Sub SampleCode()
Dim sample() As String
sample = Split("this,is,a,random,phrase", ",")
CustomQuickSort sample, LBound(sample), UBound(sample)
Dim i As Integer
For i = LBound(sample) To UBound(sample)
Debug.Print sample(i)
Next i
End Sub
如果您希望它按降序排序,请交换 SortCompare = True 和 SortCompare = False 行。