Forum Discussion
Excel Sort function on the active range
If you want to sort the data in place, you could use VBA code to sort the table when the workbook is opened, and if desired also when you switch to the relevant sheet from another sheet in the workbook.
(Sorting automatically as data are being added/edited is not a good idea, it would look very confusing.)
To do so:
1) Press Alt+F11 to activate the Visual Basic Editor.
Select Insert > Module.
Copy the following code into the module:
Sub SortData()
With Worksheets("Sheet1")
.Range("A1").CurrentRegion.Sort Key1:=.Range("J1"), Header:=xlYes
End With
End Sub
Change the name of the sheet to the one containing the table, and change A1 and J1 if the table does not start in A1.
2) Double-click ThisWorkbook under Microsoft Excel Objects in the Project Explorer pane on the left.
Copy the following code into the ThisWorkbook module:
Private Sub Workbook_Open()
Call SortData
End Sub
This will sort the data when the workbook is opened.
3) Double-click the relevant worksheet in the Project Explorer.
Copy the following code into the worksheet module:
Private Sub Worksheet_Activate()
Call SortData
End Sub
This will sort the data when you switch to the worksheet from another sheet in the same workbook.
4) Switch back to Excel.
Save the workbook as a macro-enabled workbook (.xlsm).
Make sure that you allow macros when you open the workbook.