How to Fix Excel VBA Error 1004 Sort Reference Is Not Valid

Automating data analytics and worksheet summaries in Microsoft Excel using VBA macros often involves sorting tabular datasets using Worksheet.Sort or Range.Sort. When executing sorting macros, developers frequently encounter 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. This runtime exception occurs because previous sort field definitions linger in memory, sort keys refer to cells outside the target range, or worksheet unqualified references clash across sheets.

Always Clear SortFields Before Adding New Keys

The modern Excel VBA Sort object retains previous sorting fields across macro executions. Failing to purge the collection causes conflicting sort references:

Sub SortDataSafely()
    Dim ws As Worksheet
    Dim rngData As Range
    
    Set ws = ThisWorkbook.Sheets("SalesData")
    Set rngData = ws.Range("A1:E500")
    
    ' Clear lingering sort fields to prevent Error 1004
    ws.Sort.SortFields.Clear
    
    ' Add qualified sort key
    ws.Sort.SortFields.Add2 Key:=ws.Range("B2:B500"), _
        SortOn:=xlSortOnValues, _
        Order:=xlAscending, _
        DataOption:=xlSortNormal
        
    ' Configure and apply the sort operation
    With ws.Sort
        .SetRange rngData
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

Ensure Key Ranges Match Data Bounds Exactly

A common mistake occurs when the Key parameter specifies a range with a different row count than the range passed to SetRange. If sorting rows 2 to 500, the sort key must span exactly rows 2 to 500.

Verify Sheet Protection and Merged Cell Absence

Sorting ranges that encompass horizontally merged cells or protected sheets triggers error 1004. Unmerge cells and call ws.Unprotect Password:="pass" prior to executing the sort method.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.