我正在尝试创建一个多级排序宏,而行数是动态的。我一直在搞乱一些测试数据试图让它工作,但是我不断从Excel获得1004个运行时错误。希望第二双眼睛可以帮助解决这个问题。
这是测试数据
A B C D
Num Status Junk Junk
1 Open 1 1
2 Open 2 2
3 Closed 3 3
3 Open 3 3
4 Open 4 4
6 Open 6 6
8 Open 8 8
8 Open 8 8
34 Open 34 34
456 Open 456 456
5 Closed 5 5
853 Open 853 853
2345Closed 2345 2345
234 Open 234 234
23 Closed 23 23
4 Open 4 4
76 Closed 76 76
345 Open 345 345
623 Closed 623 623
523 Open 523 523
4525Closed 4525 4525
6 Open 6 6
这是我的宏
Range("A1:D1").Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add _
Key:=Range("B1:B10"), SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:= _
"Open,Closed", DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add _
Key:=Range("A1:A10"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
另请参阅我有Range的行(" A1:A10"),希望A10成为最后一行。所以我不确定该放什么。
全心全意,
吉姆
答案 0 :(得分:2)
将您的最后一行放入变量中,然后在您的范围名称中使用该变量,就像我在下面所做的那样。我还清理了一些代码,以便于阅读和提高效率。您遇到了运行时错误,因为您错过了SetRange
方法:
Sub mySort()
Dim lngLast As Long
lngLast = Range("A" & Rows.Count).End(xlUp).Row
On Error Go to Whoa! 'in honor of Siddhart Rout (I like that :))
With Worksheets("Sheet1").Sort
.SortFields.Clear
.SortFields.Add Key:=Range("B1:B" & lngLast), SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:= _
"Open,Closed", DataOption:=xlSortNormal
.SortFields.Add Key:=Range("A1:A1" & lngLast), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SetRange Range("A1:D" & lngLast)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
On Error Go To 0
Exit Sub
Whoa!:
Msgbox "Error " & Err.Number & " " & Err.Description, vbOkOnly
End Sub