我正在尝试在一个工作表中对数据进行排序,其中列有两列 - 首先是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
答案 0 :(得分:0)
您必须首先将自定义排序顺序作为数组添加到自定义列表中。排序时,您必须排序两次。进入辅助自定义排序顺序,然后进入主要非自定义键。
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行开始排序,但没有说明你是否有标题行。