Private Sub Workbook_AfterSave(ByVal Success As Boolean)
On Error Resume Next
Range("E1").Sort Key1:=Range("E2"), Order1:=xlAscending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
End Sub
我目前正在使用此代码根据 E列中的处理日期对报告进行排序。它工作得很好,但我还必须根据优先级(高,中,低)进行另一次排序,这样每天也会在最高优先级排序。
E.g。
任务1 /高/ 12-02-18
任务二/高/ 13-02-18
任务三/中/ 13-02-18
任务四/低/ 13-02-18
任务五/高/ 14-02-18
我对VBA很陌生,非常感谢这方面的帮助。
答案 0 :(得分:1)
以下代码将按升序对E列进行排序,然后将B列与优先级排序,并使用自定义列表High,Medium,Low进行排序:
Sub foo()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set your worksheet, amend as required
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'get the last row with data on Column A
ws.Sort.SortFields.Clear
ws.Sort.SortFields.Add Key:=Range("E2:E" & LastRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ws.Sort.SortFields.Add Key:=Range("B2:B" & LastRow), SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:="High,Medium,Low", DataOption:=xlSortNormal
With ws.Sort
.SetRange Range("A1:E" & LastRow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
答案 1 :(得分:0)
Range
对象的 Sort()
方法最多允许三个排序键
所以,假设您的数据从A列到E列,并且您想要对D和E列进行排序,您可以编码:
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
With Worksheets("MySheetToSortName") ' change "MySheetToSortName" to your actual sheet to sort name
.Columns("A:E").Sort Key1:=.Range("E1"), Order1:=xlAscending, Key2:=.Range("D1"), Order2:=xlAscending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
End With
End Sub
对您要使用Sort
对象的自定义订单进行排序,例如按this post
虽然作为一个有趣的(?)解决方法坚持Sort()
方法,你可以采取以下行动:
Private Sub main()
With Worksheets("Sheet1")
With .Columns("D")
.Replace "High", "1"
.Replace "Medium", "2"
.Replace "Low", "3"
End With
.Columns("A:E").Sort Key1:=.Range("E1"), Order1:=xlAscending, Key2:=.Range("D1"), Order1:=xlAscending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
With .Columns("D")
.Replace "1", "High"
.Replace "2", "Medium"
.Replace "3", "Low"
End With
End With
End Sub