Home » excel » excel – Sub Sorting Macro

excel – Sub Sorting Macro

Posted by: admin May 14, 2020 Leave a comment


I have task list where each task is assigned a priority 1-6 in col A, with 6 being “Completed”. Each task has a task request date in col B.

I have the following code that sorts the list by priority, which leaves the completed tasks at the bottom.

Sub mcr_Sort_by_Status()
' Sort by stattus


    'Turn off screen updating so macro working/flashing does not show
    Application.ScreenUpdating = False
    ActiveWorkbook.Worksheets("Tasks").Sort.SortFields.Add Key:=Range("A8:A5000"), _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Tasks").Sort
        .SetRange Range("A7:K5000")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
    End With

End Sub

But then for the other tasks I would like to sort them by date with the latest at the top, but can’t think of how to do that programmatically.

How to&Answers:

Sort on your priority as the primary key once then reshape the range and sort the dates as the primary key in a second sort operation.

I’ll assume your dates are in column B.

Sub mcr_Sort_by_Status()

    With workSheets("Sheet1")

        with .Range(.cells(7, "A"), .cells(.rows.count, "A").end(xlup).offset(0, 10))

            .Cells.Sort Key1:=.Columns(1), Order1:=xlAscending, _
                        Orientation:=xlTopToBottom, Header:=xlyes

            with .resize(application.match(6, .columns(1), 0)-1, .columns.count)

                .Cells.Sort Key1:=.Columns(2), Order1:=xldescending, _
                            Orientation:=xlTopToBottom, Header:=xlyes

            end with

        end with

    End With

end sub