This article demonstrates how to sort a specific column in an Excel defined Table based on event code. The event macro is triggered when a record is entered and sorts the first column from small to large or A to Z.
Hey, can you do the opposite of this - not random order but this is my situation.
I have 3 rows.
A1 - Item Number
B1 - Description
C1 - Price
These will constantly be having new numbers put in.
Is there a way to have it when you add a number into the A column it will automatically sort into numerical order?
Or can I create a button that after I input all my data click it and it updates all 3 rows into the numerical order based on row A
First I'll show you how to convert a dataset into an Excel defined table. There are several things that make it easier to work with the data if you convert it to an Excel defined Table.
Create an Excel defined Table
Select any cell in your dataset.
Go to tab "Insert" on the ribbon.
Click "Table" button.
This dialog box appears:
Click OK button.
How does it work?
The event macro below sorts an Excel defined Table automatically (column A) when all cells on the same row contain a value. The animated picture above explains it all.
'Event code name
Private Sub Worksheet_Change(ByVal Target As Range)
'Dimension variables and declare data types
Dim ACell As Range
Dim ActiveCellInTable As Boolean
Dim r As Single
Dim Value As Variant
'Save changed cell to object variable ACell
Set ACell = Target
'Enable error handling
On Error Resume Next
ActiveCellInTable = (ACell.ListObject.Name = "Table1")
'Disable error handling
On Error GoTo 0
'Make sure that Excel table named Table1 exists in workbook
If ActiveCellInTable = True Then
'Subtract the relative row number of the Excel defined Table with the row number of changed cell and save the result to variable r
r = Target.Row - Target.ListObject.Range.Row + 1
'Iterate through each column in Excel defined Table
For c = 1 To ActiveSheet.ListObjects(ACell.ListObject.Name).Range.Columns.Count
'Check ff cell is empty and stop macro if so
If ActiveSheet.ListObjects(ACell.ListObject.Name).Range.Cells(r, c).Value = "" Then Exit Sub
'Continue with next column
'The With ... End With statement allows you to write shorter code by referring to an object only once instead of using it with each property.
'Clear previous sorting criteria
'Add a new sort with an ascending order
Key:=Range("Table1[[#All],[Item number]]"), SortOn:=xlSortOnValues, Order _
Where to copy the code?
Copy macro above.
Press Alt+F11 to open the VBE (Visual Basic Editor).
Doubleclick on a worksheet in the Project Explorer to open the worksheet module.
Paste code to worksheet module.
Return to Excel.
Save your workbook as a macro-enabled workbook (*.xlsm)
How to customize macro to your workbook
Change this table name Table1 to your specific table name, in the macro above.
Change also this Table1[[#All],[Item number]] to whatever table name and header name you want to sort on.