Sorting Code Error

Aviles

Board Regular
Joined
Dec 17, 2008
Messages
163
Hi all,
I'm getting the below error message when tyring to sort a range:

"Run-time error '1004': The sort reference is not valid. Make sure that it's within the data you want to sort, and the first Sort By box isn't the same or blank."

I'm using the code below, and when I press the "debug" button it's hi-lighting the ".Apply" line in yellow:

Code:
Sub Sort_Trades()
Range("C5:M50").Select
    ActiveWorkbook.Worksheets("Sort").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sort").Sort.SortFields.Add Key:=Range("C6:M50") _
        , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sort").Sort
        .SetRange Range("C5:M50")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Range("A1").Select
End Sub

I got the above code by recording a macro and it worked fine. There's proably a simple solution for this, but I have no idea what is causing the error.

Any ideas?
 

Excel Facts

Why does 9 mean SUM in SUBTOTAL?
It is because Sum is the 9th alphabetically in Average, Count, CountA, Max, Min, Product, StDev.S, StDev.P, Sum, VAR.S, VAR.P.
I believe the problem is with the Key parameter highlighted below.
It establishes the column to be used for the sort order, so it should only be one column wide.

Rich (BB code):
ActiveWorkbook.Worksheets("Sort").Sort.SortFields.Add Key:=Range("C6:M50") _
        , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal

You may add additional keys, but each one should be only one column wide.
 
Upvote 0

Forum statistics

Threads
1,215,063
Messages
6,122,935
Members
449,094
Latest member
teemeren

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top