Excel VBA Run-Time Error 1004

calendar_today Asked Dec 30, 2011
thumb_up 4 upvotes
history Updated April 16, 2026

Question posted 2011 · +6 upvotes

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

Accepted answer +4 upvotes

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

2 code variants in this answer

  • Variant 1 — 14 lines, starts with 'Sort the active rows
  • Variant 2 — 6 lines, starts with ActiveWorkbook.Worksheets("Product Backlog").Range("A4:F51"…

Excel VBA objects referenced (3)

Top excel-vba Q&A (6)

+4 upvotes ranks this answer #134 out of 136 excel-vba solutions on this site .