Forum Discussion

KTrask8's avatar
KTrask8
Copper Contributor
Aug 22, 2024

Macro Code for Auto Sort

I have a complaint log spreadsheet that tracks incident date in column D starting at D3. I have it to manually sort with most recent on top but I want a code to auto sort that was as information is input. I know how to open the code but I just don't know what to plug in to make it auto sort.

  • KTrask8 

    Sorting a range when data are being entered is very confusing: a row might disappear from sight when you enter a date.

    So I'd sort the data when the workbook is opened or when the sheet with the data is activated.

    For example:

    • Press Alt+F11 to activate the Visual Basic Editor.
    • Double-click ThisWorkbook under Microsoft Excel Objects
    • Copy the following code into the ThisWorkbook module.
    • Switch back to Excel.
    • Save the workbook as a macro-enabled workbook (*.xlsm).
    Private Sub Workbook_Open()
        ' Change the worksheet name as needed
        With Worksheets("Complaint Log")
            .Range("D3").CurrentRegion.Sort Key1:=.Range("D3"), Order1:=xlDescending, Header:=xlNo
        End With
    End Sub

Resources