Sort values in a table (vba)
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 coloum 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 numberical order based on row A
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 coloum 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 numberical order based on row A
Answer:
Create a table
Sort values
Automatically sort values (vba)
The macro below sorts a table automatically (column A) when all cells in the current row have a value. See gif animation.
VBA code
Private Sub Worksheet_Change(ByVal Target As Range)
Dim ACell As Range
Dim ActiveCellInTable As Boolean
Dim r As Single
Dim Value As Variant
Set ACell = Target
On Error Resume Next
ActiveCellInTable = (ACell.ListObject.Name = "Table1")
On Error GoTo 0
If ActiveCellInTable = True Then
r = Target.Row - Target.ListObject.Range.Row + 1
For c = 1 To ActiveSheet.ListObjects(ACell.ListObject.Name).Range.Columns.Count
If ActiveSheet.ListObjects(ACell.ListObject.Name).Range.Cells(r, c).Value = "" Then Exit Sub
Next c
With ActiveSheet.ListObjects(ACell.ListObject.Name).Sort
.SortFields.Clear
.SortFields.Add _
Key:=Range("Table1[[#All],[Item number]]"), SortOn:=xlSortOnValues, Order _
:=xlAscending, DataOption:=xlSortNormal
.Apply
End With
End If
End Sub
Download excel *.xlsm file
Related posts:
Excel vba: Filter a table using the selection change event
Select a cell in a table and the chart updates automatically (vba)





















I believe you can replace these 5 lines from your code...
Dim r As Single .... r = Target.Row - Target.ListObject.Range.Row + 1 For c = 1 To ActiveSheet.ListObjects(ACell.ListObject.Name).Range.Columns.Count If ActiveSheet.ListObjects(ACell.ListObject.Name).Range.Cells(r, c).Value = "" Then Exit Sub Next cwith this single line of code...
If Not Intersect(Target.EntireRow, Target.ListObject.Range).Find("") Is Nothing Then Exit SubRick Rothstein (MVP - Excel),
I appreciate your comments, great value!
Where in this code do I modify if I want to sort by a different column then the first one?
Wen,
Replace this Table1[[#All],[Item number]] with your table name and column