我设法编写代码,一旦选择了下拉选项,就会自动对数据进行排序。此代码如下:
Private Sub Worksheet_Change(ByVal Target As Range)
Range("A7:AF200").Sort key1:=Range("D7:D200"), _
order1:=xlAscending, Header:=xlNo
Dim lastrow As Long
lastrow = Cells(Rows.Count, 2).End(xlUp).Row
Range("A7:AF" & lastrow).Sort key1:=Range("D7:D" & lastrow), _
order1:=xlAscending, Header:=xlNo
ActiveWorkbook.Worksheets("Job List").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Job List").Sort.SortFields.Add Key:=Range("D:D"), _
SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:= _
"Pre-Design,Design,Tender,Construction,Post Construction", DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Job List").Sort
.SetRange Range("A7:AE9999")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
但是,在按自定义顺序对作业列表进行排序后,我需要将数据按照单元格A7中输入的作业编号进行升序排序:A
例如:
变为
自动
答案 0 :(得分:1)
可以通过添加额外的排序
来对多个列进行排序Private Sub Worksheet_Change(ByVal Target As Range)
Range("A7:AF200").Sort key1:=Range("D7:D200"), _
order1:=xlAscending, Header:=xlNo
Dim lastrow As Long
lastrow = Cells(Rows.Count, 2).End(xlUp).Row
Range("A7:AF" & lastrow).Sort key1:=Range("D7:D" & lastrow), _
order1:=xlAscending, Header:=xlNo
ActiveWorkbook.Worksheets("Job List").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Job List").Sort.SortFields.Add Key:=Range("D:D"), _
SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:= _
"Pre-Design,Design,Tender,Construction,Post Construction", DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Job List").Sort.SortFields.Add Key:=Range("A7:A9999"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Job List").Sort
.SetRange Range("A7:AE9999")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub