Sorting Code Error

Aviles

Board Regular
Joined
Dec 17, 2008
Messages
161
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

Convert text numbers to real numbers
Select a column containing text numbers. Press Alt+D E F to quickly convert text to numbers. Faster than "Convert to Number"

Jerry Sullivan

MrExcel MVP
Joined
Mar 18, 2010
Messages
8,787
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.
 

Forum statistics

Threads
1,141,019
Messages
5,703,771
Members
421,315
Latest member
awaisnazir139

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
Top