我怎么知道我的排序是否在excel vba中运行?

时间:2015-03-17 21:33:08

标签: excel vba sorting

我在排序数据时录制了以下宏:

Sub sort_sheet_test()
    ActiveWindow.ScrollRow = 1
    ActiveWindow.ScrollColumn = 1
    Range("A1:AB40905").Select
    ActiveWorkbook.Worksheets("flurry_an_output.csv").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("flurry_an_output.csv").Sort.SortFields.Add Key:= _
    Range("AB2:AB40905"), SortOn:=xlSortOnValues, Order:=xlAscending, _
    DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("flurry_an_output.csv").Sort
        .SetRange Range("A1:AB40905")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

然后我编写了自己的函数,一般用于其他工作表......等等:

Function sort_sheet_last_column(sheet_name As String)

    Dim rows1 As Long
    rows1 = Get_Rows_Generic(sheet_name, 1) '  get the number of rows in the sheet

    Dim columns1 As Integer
    columns1 = Range(find_last_column(sheet_name)).column ' get the number of columns in the sheet

    Dim sort_range As Range
    Dim key_range As Range
    With Worksheets(sheet_name)
        Set sort_range = .Range(.Cells(1, 1), .Cells(rows1, columns1)) ' set up range: the whole used portion of the sheet
        Set key_range = .Range(.Cells(1, columns1), .Cells(rows1, columns1))
    End With

    With Worksheets(sheet_name).Sort
        .SortFields.Clear
        .SortFields.Add Key:=key_range, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        .SetRange sort_range
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply

    End With

End Function

它似乎是根据正确的键重新排序行,但我怎么知道我的版本是否1)工作(很难知道是否正确地订购了超过40,000行,以及2)我怎么知道是否其余的数据是按照正确的顺序排列的吗?

1 个答案:

答案 0 :(得分:0)

我总是使用Sheet.Range.Sort而不是Sheet.Sort

 lLastRow = LastUsedRow(shMain)

 shMain.Range("A1:W" & lLastRow).SORT Key1:=.Range("B2"), _
                                      Order1:=xlAscending, _
                                      Header:=xlYes, _
                                      OrderCustom:=1, _
                                      MatchCase:=False, _
                                      Orientation:=xlTopToBottom, _
                                      DataOption1:=xlSortNormal

从未对此范围进行排序存在问题,您可以添加Key2,Order2和DataOption2以按多列排序