Run time error 1004 when trying to sort data on three different values

£可爱£侵袭症+ 提交于 2019-12-13 17:42:27

问题


I've read at least fifteen different articles on this and tried a number of different possible solutions. I am trying to use the VBA code below to sort a worksheet of variable size by three different levels.

When I step through the code I get an error 1004 at the .apply argument of the sort.

Run-time error '1004':

The sort reference is not vald. Make sure that it's within the data you want to sort, and the first Sort By box isn't the same or blank.

Can anyone suggest a reason why or a solution to this problem?

Sub Subbing()

Dim LastCell as String

Range("A2").End(xlDown).Select

LastCell = Selection.Offset(0, 13).Address
Worksheets("Sheet1").Activate

With ActiveWorkbook.Worksheets("Sheet1").Sort
        .SortFields.Clear
        .SetRange Range("A2", LastCell)
        .SortFields.Add Key:=ActiveWorkbook.Worksheets("Sheet1").Range("R2"), _ SortOn:=xlSortOnValues, Order:=xlAscending
        .SortFields.Add Key:=ActiveWorkbook.Worksheets("Sheet1").Range("S2"), _ SortOn:=xlSortOnValues, Order:=xlAscending
        .SortFields.Add Key:=ActiveWorkbook.Worksheets("Sheet1").Range("D2"), _ SortOn:=xlSortOnValues, Order:=xlAscending
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply

End With
End Sub

I look forward to your responses. I know this is a common question but I have tried all of the widely suggested methods of resolving my issue and to no avail.

Kind Regards

Pete


回答1:


Looks to me like you selected A:N to sort, but are sorting on the values of R and S as well as D. Run it through Step mode and put a watch on LastCell - if I'm right, that won't be far enough over for you to actually sort what you want.




回答2:


... Your criteria range is outside of the sort area - You can't do this.

What I mean is that your sort range will be between Column A and Column N (13 columns after A), but your criteria are in Columns R & S.

If you extend your sort range, all will work.

Hope this fixes everything.



来源:https://stackoverflow.com/questions/15026539/run-time-error-1004-when-trying-to-sort-data-on-three-different-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!