Home » excel » excel vba – Run time error 1004 when trying to sort data on three different values

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

Posted by: admin May 14, 2020 Leave a comment


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


LastCell = Selection.Offset(0, 13).Address

With ActiveWorkbook.Worksheets("Sheet1").Sort
        .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

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


How to&Answers:

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.


… 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.