Forum

Any ideas how to so...
 
Notifications
Clear all

Any ideas how to sort a table (.ListObjects(1)) by column 3, then by column 4?

5 Posts
3 Users
0 Reactions
1,795 Views
(@gobsheite)
Posts: 11
Active Member
Topic starter
 

Hi. Im trying to sort a table, I tried recording a macro to get an idea but it produces loads of code just for one click

 

Any ideas how to sort a table (.ListObjects(1)) by column 3, then by column 4?

 
Posted : 15/06/2022 10:42 am
Philip Treacy
(@philipt)
Posts: 1630
Member Admin
 

Hi,

Try this

 

Sub SortCols()

ActiveSheet.ListObjects("Table1").Sort.SortFields.Clear

Range("Table1").Sort Key1:=Range("Table1[[#All],[Col3]]"), Key2:=Range("Table1[[#All],[Col4]]"), Header:=xlYes

End Sub

 

Change Col3 and Col4 to the column names.  Be default this sorts in Ascending order.  If you want something else you can use the Order parameters e.g.

 

Sub SortCols()

ActiveSheet.ListObjects("Table1").Sort.SortFields.Clear

Range("Table1").Sort Key1:=Range("Table1[[#All],[Col3]]"), Key2:=Range("Table1[[#All],[Col4]]"), Header:=xlYes, Order1:=xlAscending, Order2:=xlDescending

End Sub

 

regards

Phil

 
Posted : 15/06/2022 10:22 pm
(@gobsheite)
Posts: 11
Active Member
Topic starter
 

Hi. I'm struggling to incorporate that into my existing With statements

Any ideas?

 

With ActiveWorkbook.ActiveSheet

With .ListObjects(1)

.Sort Key1:=Range(.Name & "[#All],[Col3]"), Key2:=Range(.Name & "[#All],[Col4]"), Header:=xlYes

End With

End With

 
Posted : 22/06/2022 4:48 am
(@debaser)
Posts: 837
Member Moderator
 

You could shorten to:

With ActiveWorkbook.ActiveSheet.ListObjects(1)
.Range.Sort Key1:=.ListColumns(3), Key2:=.ListColumns(4), Header:=xlYes
End With

 
Posted : 22/06/2022 8:14 am
(@gobsheite)
Posts: 11
Active Member
Topic starter
 

Great Thanks.

And it also answered my question as to why you keep having to define the same sort range over and over, which was making me very nervous because i dont want to mash up a whole days works. Answer is. You don't

 
Posted : 23/06/2022 3:41 am
Share: