按日期对行进行排序

时间:2020-07-10 06:19:24

标签: excel vba sorting date rows

我是VBA的新手,我的桌子有问题。如果我的表具有标题并且日期从A2列开始,则表的大小最大为R。我需要一种按日期自动对行进行排序的方法。表的大小在不断增长,因此,如果需要的话,如何扩展选择范围是更可取的。

ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add2 Key:=Range( _
    "A2:A" & lastrow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
    .SetRange Range("A1:Q" & lastrow)
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
ActiveCell.SpecialCells(xlLastCell).Select

结束子

1 个答案:

答案 0 :(得分:0)

将数据放入实际表格中-突出显示数据,然后从工具栏中选择插入〜表格
您的表应命名为 Table1 (您可以手动更改此表)。

Sub Test()

    Dim MyTable As ListObject
    Set MyTable = ThisWorkbook.Worksheets("Sheet1").ListObjects("Table1")
    
    With MyTable
        .Sort.SortFields.Clear
        .Sort.SortFields.Add2 _
            Key:=Range("Table1[MyDateColumn]"), SortOn:=xlSortOnValues, Order:=xlAscending, _
            DataOption:=xlSortNormal 'Change MyDateColumn to the name of your date column.
            
        With .Sort
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .Apply
        End With
    End With
    
End Sub

您不需要包括xlPinYin方法