Sorting using a custom order in excel gives error

2019-07-26 19:52发布

I'm trying to sort data in a sheet with several columns by two of the columns -- first by column B (alphabetically), then by column C (using the custom order "G, D, M, F" -- these are the only values that occur in the column). However, when I try to run the code, I get the error

1004 - Unable to get the Sort property of the Range class

So here's what I'm working with. Earlier in the code I have

Dim lastrow As Long
lastrow = Cells(Rows.Count, 2).End(xlUp).Row

Then here's the part where I get the error:

Range("A2:Y" & lastrow).Sort.SortFields. _
Add Key:=Range("C2:C" & lastrow), SortOn:=xlSortOnValues, Order:=xlAscending, _
DataOption:=xlSortNormal
Range("A2:Y" & lastrow).Sort.SortFields. _
Add Key:=Range("B2:B" & lastrow), SortOn:=xlSortOnValues, Order:=xlAscending, _
CustomOrder:="G,D,M,F", DataOption:=xlSortNormal

1条回答
叼着烟拽天下
2楼-- · 2019-07-26 20:33

You are going to have to add the custom sort order into the custom lists as an array first. When sorting, you will have to sort twice. Once on the secondary custom sort order and then on the primary non-custom key.

Dim vCOLs As Variant

vCOLs = Array("G", "D", "M", "F")

With Application
    '.ScreenUpdating = False
    '.EnableEvents = False
    .AddCustomList ListArray:=vCOLs
End With

With Worksheets("sheet2")
    .Sort.SortFields.Clear
    With .Cells(1, 1).CurrentRegion
        'first sort on the secondary custom sort on column B
        .Cells.Sort Key1:=.Columns(2), Order1:=xlAscending, _
                    Orientation:=xlTopToBottom, Header:=xlYes, _
                    OrderCustom:=Application.CustomListCount + 1
        'next sort on the primary key; column C
        .Cells.Sort Key1:=.Columns(3), Order1:=xlAscending, _
                    Orientation:=xlTopToBottom, Header:=xlYes

    End With
    .Sort.SortFields.Clear
End With

I'm not entirely sure what is going on with your row 1. Your original code starts the sort in row 2 but gives no indication whether you have a header row or not.

查看更多
登录 后发表回答