|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
增加了Z-A排序的内容。
以及,数组内排序,增加了空白单元格自动排最后。
首先,是Excel自带排序功能的录制代码:- Sub px1()
- m = [a1].End(2).Column
- n = InputBox("Please input sort columns number:" & vbCr & "less then <= " & m, "sort", 0)
- If n = "" Then Exit Sub Else n = Val(n)
- s = InputBox("Please select s=0 for Ascending or s=1 for Descending Order", "sort", 0)
- tm = Timer
-
- If n = 0 Or n > m Then
- MsgBox "Will be Restore (Sort by No.1)"
- tm = Timer
- If s = 0 Then
- [a1].CurrentRegion.Sort Key1:=[a1], Order1:=xlAscending, Header:=xlYes
- ElseIf s = 1 Then
- [a1].CurrentRegion.Sort Key1:=[a1], Order1:=xlDescending, Header:=xlYes
- End If
- MsgBox Format(Timer - tm, "0.000")
- Exit Sub
- End If
- If s = 0 Then
- For i = 1 To n
- [a1].CurrentRegion.Sort Key1:=[a1].Offset(0, m - n + i - 1), Order1:=xlAscending, Header:=xlYes
- Next
- ElseIf s = 1 Then
- For i = 1 To n
- [a1].CurrentRegion.Sort Key1:=[a1].Offset(0, m - n + i - 1), Order1:=xlDescending, Header:=xlYes
- Next
- End If
-
- MsgBox Format(Timer - tm, "0.000")
- End Sub
复制代码 下面是数组操作代码:- Sub px2()
- m = [a1].End(2).Column
- n = InputBox("Please input sort columns number:" & vbCr & "less then <= " & m, "sort", 0)
- If n = "" Then Exit Sub Else n = Val(n)
- s = InputBox("Please select s=0 for Ascending or s=1 for Descending Order", "sort", 0)
- tm = Timer
-
- ReDim arr(1, 1)
- x = [a1].CurrentRegion
- arr = x
-
- If n = 0 Or n > m Then
- MsgBox "Will be Restore (Sort by No.1)"
- tm = Timer
- ' [a1].CurrentRegion.Sort Key1:=[a1], Header:=xlYes
- szpx arr, m, 1, s, 1
- [a1].CurrentRegion = arr
- MsgBox Format(Timer - tm, "0.000")
- Exit Sub
- End If
-
- For i = 1 To n
- szpx arr, m, m - n + i, s, 1
- ' [a1].CurrentRegion = arr
- Next
- [a1].CurrentRegion = arr
-
- MsgBox Format(Timer - tm, "0.000")
- End Sub
复制代码 最后,是数组内排序的过程代码:- Sub szpx(x(), m, n, s, h)
- For i = LBound(x) + h To UBound(x)
- If x(i, n) = "" Then p = p & "," & i
- Next
- If p <> "" Then
- y = x
- k = h
- For j = LBound(x) + h To UBound(x)
- If x(j, n) <> "" Then
- k = k + 1
- For l = 1 To m
- y(k, l) = x(j, l)
- Next
- End If
- Next
-
- q = Split(p, ",")
- b = UBound(q)
- For j = 1 To b
- k = k + 1
- For l = 1 To m
- y(k, l) = x(q(j), l)
- Next
- Next
- x = y
- End If
-
- For i = LBound(x) + h To UBound(x) - b
- t = x(i, n)
- p = "," & i
- For j = i + 1 To UBound(x) - b
- If s = 0 And t > x(j, n) Then
- t = x(j, n)
- p = "," & j
- ElseIf s = 1 And t < x(j, n) Then
- t = x(j, n)
- p = "," & j
- ElseIf t = x(j, n) Then
- p = p & "," & j
- End If
- Next
-
- q = Split(p, ",")
- c = UBound(q)
-
- y = x
- For j = 1 To c
- For l = 1 To m
- y(i + j - 1, l) = x(q(j), l)
- Next
- x(q(j), n) = ""
- Next
-
- k = i + c
- For j = i To UBound(x) - b
- If x(j, n) = "" Then
- If c = 1 Then Exit For Else c = c - 1
- Else
- For l = 1 To m
- y(k, l) = x(j, l)
- Next
- k = k + 1
- End If
- Next
-
- x = y
-
- Next
- End Sub
复制代码 最后,发现数组内排序操作,当数据量稍多就很慢了。
|
|