Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA Run-Time Error 1004

Tags:

excel

vba

I am using VBA for Excel 2010 and randomly receiving the following error:

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

This is the code

'Sort the active rows
With ActiveWorkbook.Worksheets("Product Backlog").Sort
    .SetRange Range("A4:F51")
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
like image 705
Aaron Avatar asked Oct 09 '22 03:10

Aaron


1 Answers

The sort by box is blank, that is your problem. I never have used a Sort object like your doing, but I can see that you have not defined a key, or a range to sort by, just the range to be sorted. A key should be defined such as Range("A4") or something. I looked it up, it should have .sortfields.add (range) in it, such as:

'Sort the active rows

    With ActiveWorkbook.Worksheets("Product Backlog").Sort
        .SetRange Range("A4:F51")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin

        .SortFields.Add Key:=Range("A4:F51").Columns(1), SortOn:=xlSortOnValues, _
         Order:=xlDescending, DataOption:=xlSortNormal

        .Apply
    End With

I use the Sort function as follows:

ActiveWorkbook.Worksheets("Product Backlog").Range("A4:F51").Sort _
    Key1:= ActiveWorkbook.Worksheets("Product Backlog").Range("A4:F51").Columns(1), _
    Header:= xlYes, _
    Orientation:=xlSortColumns, _
    MatchCase:=False, _
    SortMethod:=xlPinYin
like image 175
Motes Avatar answered Oct 15 '22 11:10

Motes