ethan finger
ethan finger

Reputation: 21

VBA: Sorting worksheets with macro

As shown in this image

This is a picture of the error

My sort syntax is wrong and I don't understand why.

I get

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.

Sub Sort()
'
' Sort Macro

Dim rowNum As Variant

Dim columnNum As Variant
Dim sortField As Range
Dim keySort As Range

rowNum = Worksheets("Updated 1.0").Range("A1").End(xlDown).row
MsgBox (rowNum)

columnNum = Worksheets("Updated 1.0").Range("A1").End(xlToRight).column
MsgBox (columnNum)

With Worksheets("Updated 1.0")
    Set sortField = Range(.Cells(2, 1), .Cells(rowNum, columnNum))
    Set keySort = Range("A1")
    sortField.Sort Key1:=keySort, Order1:=xlDescending, MatchCase:=False, 
Orientation:=xlSortRows

End With

Upvotes: 2

Views: 103

Answers (1)

Tim Williams
Tim Williams

Reputation: 166196

You were missing some . inside the With but also the sort was was not correct I think.

This worked for me:

Sub Sort()

    Dim sht As Worksheet
    Dim sortField As Range
    Dim keySort As Range

    Set sht = Worksheets("Updated 1.0")

    With sht
        Set sortField = .Range("A1").CurrentRegion
        Set keySort = .Range("A1")
        sortField.Sort Key1:=keySort, Order1:=xlDescending, MatchCase:=False, _
                       Orientation:=xlSortRows
    End With

End Sub

Upvotes: 2

Related Questions