Sorting using a custom order in excel gives error 1004
我正在尝试按两列中的两列对工作表中的数据进行排序-首先按列B(按字母顺序),然后按列C(使用自定义顺序" G,D,M,F")- 列中唯一出现的值)。 但是,当我尝试运行代码时,出现错误
1  | 1004 - Unable to get the Sort property of the Range class  | 
这就是我正在处理的内容。 我在代码的前面
1 2  | Dim lastrow As Long lastrow = Cells(Rows.Count, 2).End(xlUp).Row  | 
然后这是我得到错误的部分:
1 2 3 4 5 6  | 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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24  | 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  | 
我不完全确定第1行的情况。您的原始代码在第2行中开始排序,但没有指示您是否有标题行。