在Excel中使用自定义顺序sorting会出现错误1004

我试图在一个工作表中排列数据,其中有两列,首先是列B(按字母顺序),然​​后是C列(使用自定义顺序“G,D,M,F”) – 这些是在列中出现的唯一值)。 但是,当我尝试运行代码时,出现错误

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

所以这是我正在与之合作。 早些时候在我的代码

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

那么这里是我得到错误的部分:

 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 

您将不得不首先将自定义sorting顺序作为数组添加到自定义列表中。 sorting时,你将不得不sorting两次。 一旦在辅助自定义sorting顺序上,然后在主要的非自定义键上。

 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 

我不完全确定你的第一行是怎么回事。你原来的代码在第二行开始sorting,但是不知道你是否有一个标题行。