Is this the cleanest way to code the sorting of a

2019-08-21 02:03发布

Here's the code I've written to sort a table based on two columns then deselect the table once that's done. Is there a cleaner way to code this?

Sub SortTable()

    ' Sorts table

    Worksheets("Data").ListObjects("Table").Sort.SortFields. _
        Clear
    Worksheets("Data").ListObjects("Table").Sort.SortFields. _
        Add Key:=Range("Table[Date]"), SortOn:=xlSortOnValues, Order:= _
        xlAscending, DataOption:=xlSortNormal
    Worksheets("Data").ListObjects("Table").Sort.SortFields. _
        Add Key:=Range("Table[Info]"), SortOn:=xlSortOnValues, Order:= _
        xlAscending, DataOption:=xlSortNormal
    With Worksheets("Data").ListObjects("Table").Sort
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

    ' Clears table selection

    With Worksheets("Data")
        .Activate
        .Range("A1").Select
    End With

End Sub

2条回答
Luminary・发光体
2楼-- · 2019-08-21 02:24

You can do it tidier by moving your With

Sub SortTable()

    ' Sorts table
     With Worksheets("Data").ListObjects("Table").Sort

        With .SortFields
            .Clear
            .Add Key:=Range("Table[Date]"), SortOn:=xlSortOnValues, Order:= _
                xlAscending, DataOption:=xlSortNormal
            .Add Key:=Range("Table[Info]"), SortOn:=xlSortOnValues, Order:= _
                xlAscending, DataOption:=xlSortNormal
         End With
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

    ' Clears table selection

    With Worksheets("Data")
        .Activate
        .Range("A1").Select
    End With

End Sub
查看更多
疯言疯语
3楼-- · 2019-08-21 02:25

If you know the position of the columns to sort, then this method seems to clean things up.

With Sheets("data").ListObjects("Table")
    .Range.Sort Key1:=.ListColumns(2), Order1:=xlAscending, _
                Key2:=.ListColumns(4), Order2:=xlAscending, _
                Orientation:=xlTopToBottom, Header:=xlYes
    .Parent.Range("A1").Select
End With

For the above, the Date list column is 2 and Info is 4. If you don't know the column ordinals then you need to reference the columns from the parent worksheet.

With Sheets("data").ListObjects("Table")
    .Range.Sort Key1:=.Parent.Range("Table[Date]"), Order1:=xlAscending, _
                Key2:=.Parent.Range("Table[Info]"), Order2:=xlAscending, _
                Orientation:=xlTopToBottom, Header:=xlYes
    .Parent.Range("A1").Select
End With
查看更多
登录 后发表回答