我怎样才能通过数据排序?

时间:2011-11-30 03:11:35

标签: excel excel-vba vba

我有一个宏按特定列对行进行排序,问题是我每次添加新行时都要手动设置要排序的行数范围(即A2:A174)。如何更改我的代码,以便它仅使用数据对所有行进行排序,这样我就不必每次添加新行时都进入代码并更改范围。

Sub SortByName()

  SortByName Macro

    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("A2:A174") _
        , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet1").Sort
        .SetRange Range("A1:H174")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Range("A1").Select
End Sub
Sub SortByDate()

非常感谢您的智慧!

1 个答案:

答案 0 :(得分:3)

类似这样的东西,它在A中寻找标记范围的最后一个单元格。

Sub SortByName()
    Dim ws As Worksheet
    Dim rng1 As Range
    Set ws = Sheets("Sheet1")
    Set rng1 = ws.Range(ws.[a1], Cells(Rows.Count, "A").End(xlUp))
    ws.Sort.SortFields.Clear
    ws.Sort.SortFields.Add Key:=rng1 _
                                , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet1").Sort
        .SetRange rng1.Resize(rng1.Rows.Count, 8)
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Application.Goto ws.[a1]
End Sub