Vba 在excel中使用自定义顺序排序时出现错误1004
我正在尝试按两列对具有多个列的工作表中的数据进行排序——首先按B列(字母顺序),然后按C列(使用自定义顺序“G,D,m,F”——这是该列中唯一出现的值)。然而,当我试图运行代码时,我得到了错误Vba 在excel中使用自定义顺序排序时出现错误1004,vba,excel,sorting,Vba,Excel,Sorting,我正在尝试按两列对具有多个列的工作表中的数据进行排序——首先按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 下面是我得到错误的部分
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
首先必须将自定义排序顺序作为数组添加到自定义列表中。排序时,您必须排序两次。在次自定义排序顺序上,然后在主非自定义键上
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
我不完全确定你的第一排是怎么回事。原始代码在第2行开始排序,但没有指示是否有标题行。您必须首先将自定义排序顺序作为数组添加到自定义列表中。排序时,您必须排序两次。在次自定义排序顺序上,然后在主非自定义键上
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
我不完全确定你的第一排是怎么回事。您的原始代码在第2行开始排序,但没有指示您是否有标题行。您使用的Excel版本是什么?同样可能相关的
CustomOrder:=“G,D,M,F”,DataOption:=xlSortNormal
对于此部分,每个G,D,M元素是单独的还是作为一个?您使用的是什么版本的Excel?也可能相关的CustomOrder:=“G,D,M,F”,DataOption:=xlsort正常的
对于这部分来说,每个G,D,M元素是分开的还是作为一个?这非常有效,非常感谢。第1行确实是标题行,我可能应该提到这一点。这非常有效,非常感谢。第1行实际上是标题行,我可能应该提到这一点。