Search code examples
vbaexcelsortingruntime-errorexcel-2007

Sort a sheet by the value of a column since the second line


I want to sort the sheet according to the value(Date) of a column(new-old) from the second row till the end.
I wrote the code, but there's always an error : 1004, sort reference is not valid. Does someone happen to know the solution?
Thank you.
Workbooks("Task2.xlsm").Worksheets("Data").Column("A:CA").Sort key1:=Range("H2"), order1:=xlDescending, Header:=xlYes


Solution

  • I recorded a macro and I found the answer(it can be simplified) :

        Workbooks("Task2.xlsm").Worksheets("Data").AutoFilter.Sort.SortFields.Clear
        Workbooks("Task2.xlsm").Worksheets("Data").AutoFilter.Sort.SortFields.Add Key:=Range("H1"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortTextAsNumbers
        With Workbooks("Task2.xlsm").Worksheets("Data").AutoFilter.Sort
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With