VBA to sort table by column B, then by column C

gekco

New Member
Joined
Nov 15, 2023
Messages
2
Office Version
  1. 365
Platform
  1. Windows
Hello Excel savants,

I am trying to get a table to sort by "Start Date" first, then sort by "Start Time". I have a macro that sorts by the date working, but would like to sort items on the same date by start time. Is that possible?

VBA Code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim SalesTable As ListObject
Dim SortCol As Range

Set SalesTable = ActiveSheet.ListObjects("Table7")
Set SortCol = Range("Table7[Start Date]")

If Not Intersect(Target, SortCol) Is Nothing Then
    With SalesTable.Sort
        .SortFields.Clear
        .SortFields.Add Key:=SortCol, Order:=xlAscending
        .Header = xlYes
        .Apply
    End With
End If

End Sub
 

Excel Facts

Fastest way to copy a worksheet?
Hold down the Ctrl key while dragging tab for Sheet1 to the right. Excel will make a copy of the worksheet.
I think you should be able to do it just by adding a 2nd sort key.
VBA Code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim SalesTable As ListObject
Dim SortCol As Range, SortCol2 As Range

Set SalesTable = ActiveSheet.ListObjects("Table7")
Set SortCol = Range("Table7[Start Date]")
Set SortCol2 = Range("Table7[Start Time]")

If Not Intersect(Target, SortCol) Is Nothing Then
    With SalesTable.Sort
        .SortFields.Clear
        .SortFields.Add Key:=SortCol, Order:=xlAscending
        .SortFields.Add Key:=SortCol2, Order:=xlAscending
        .Header = xlYes
        .Apply
    End With
End If

End Sub
 
Upvote 1
Solution
I figured that would be the answer, but as I am still learning how to utilize a lot of these functions in Excel, I could not figure how to make it work. Thank you so much, this worked for me.
 
Upvote 0
Glad it worked for you. Welcome to MrExcel.
 
Upvote 0

Forum statistics

Threads
1,224,828
Messages
6,181,217
Members
453,024
Latest member
Wingit77

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top