如何基于一个参数进行排序,然后在VBA中进行排序?

时间:2018-03-16 16:29:32

标签: excel-vba vba excel

我设法编写代码,一旦选择了下拉选项,就会自动对数据进行排序。此代码如下:

    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

例如:

  • 110.05 ClientABC Pre-Design
  • 21.02 ClientXYZ Pre-Design
  • 84.10 ClientNEW Pre-Design

变为

  • 21.02 ClientXYZ Pre-Design
  • 84.10 ClientNEW Pre-Design
  • 110.05 ClientABC Pre-Design

自动

1 个答案:

答案 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