简体   繁体   中英

Sort a column in descending order with unknown number of cells

I am trying to sort column A in descending order with unknown number of cells.

Getting run-time error - Method 'Sort' of object'_Worksheet' failed.

This code was working until recently when I got a new laptop with a different version of Excel.

lastrow = Cells(Rows.Count, 1).End(xlUp).Row

Range("A1").Select
ActiveWorkbook.Worksheets("New Working").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("New Working").Sort.SortFields.Add Key:=Range("A1") _
    , SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("New Working").Sort
    .SetRange Range("A2:AT" & lastrow)
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

The issue might come from the fact that you aren't fully qualifying your Worksheet when getting the value for the Last Row, so Excel would be looking at the ActiveSheet rather than the one you are wanting, I would suggest using something like the code below, where it is fully qualified:

Sub foo()
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("New Working")
lastrow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
ws.Sort.SortFields.Clear
ws.Sort.SortFields.Add Key:=ws.Range("A1"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
    With ws.Sort
        .SetRange ws.Range("A1:AT" & lastrow)
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM