Sorting Code Error

Aviles

Board Regular
Joined
Dec 17, 2008
Messages
173
Office Version
  1. 365
Platform
  1. Windows
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

Format cells as currency
Select range and press Ctrl+Shift+4 to format cells as currency. (Shift 4 is the $ sign).
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,224,566
Messages
6,179,553
Members
452,928
Latest member
101blockchains

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