vba哪种排序最好
展开全部
希尔排序:
Sub 希尔排序()
arr = Array(0, 1, 10, 2, 7, 4, 2, 9, 3, 6) '事例数组,其中下标为0的数不参入排序
z = UBound(arr) - LBound(arr) + 1
j = 1
If z > 13 Then
Do While j < z
j = j * 3 + 1
Loop
j = j \ 9
End If
Do While j
For x = LBound(arr) + j To UBound(arr)
t = arr(x)
For y = x - j To LBound(arr) Step -j
If arr(y) <= t Then Exit For
arr(y + j) = arr(y)
Next y
arr(y + j) = t
Next x
j = j \ 3
Loop
MsgBox "排序前:1,10,2,7,4,2,9,3,6" & vbNewLine & "排序后:" & arr(1) & "," & arr(2) & "," & arr(3) & _
"," & arr(4) & "," & arr(5) & "," & arr(6) & "," & arr(7) & "," & arr(8) & "," & arr(9)
'输出结果,其中vbNewLine为换行标志
End Sub
一般排序量小用插入排序:
Sub 插入排序()
arr = Array(0, 1, 10, 2, 7, 4, 2, 9, 3, 6) '事例数组,其中下标为0的数不参入排序
n = 9 '元素个数
For i = 2 To n '外循环次数
t = arr(i) '记录要插入的值
For j = i - 1 To 1 Step -1 '内循环
If arr(j) <= t Then Exit For
arr(j + 1) = arr(j)
Next j
arr(j + 1) = t
Next i
MsgBox "排序前:1,10,2,7,4,2,9,3,6" & vbNewLine & "排序后:" & arr(1) & "," & arr(2) & "," & arr(3) & _
"," & arr(4) & "," & arr(5) & "," & arr(6) & "," & arr(7) & "," & arr(8) & "," & arr(9)
'输出结果,其中vbNewLine为换行标志
End Sub
如果是单元格排序:
Sub 升序()
Range("A1:C" & Cells(Rows.Count, 2).End(3).Row).Sort key1:=[B1], order1:=xlAscending '升序
End Sub
Sub 降序()
Range("A1:C" & Cells(Rows.Count, 2).End(3).Row).Sort key1:=[B1], order1:=xlDescending '降序
'Rows.Count=本工作表总行数
'Cells(Rows.Count, 2).End(3).Row =第2列最后非空单元格的行号
'Range("A1:C" & Cells(Rows.Count, 2).End(3).Row) =要排序的区域
'Sort key1:=[B1] =按[B1]为关键字排序
'order1:=xlDescending =降序
'order1:=xlAscending =升序
End Sub
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询