BobtBuilder
New Member
- Joined
- Sep 1, 2023
- Messages
- 45
- Office Version
- 365
- Platform
- Windows
I have a table and every time I add a row I would like it to dynamically sort by date but keep me on the activecell. But when I sort it brings me to the cell number i was originally on and not the one i was working on. The active cell changes number on sort.
Here is the code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim tbl As ListObject
Set tbl = Me.ListObjects(1) ' Assuming your table is the first ListObject on the sheet
' Check if the changed cell is within the table
If Not Intersect(Target, tbl.ListColumns("Date").DataBodyRange) Is Nothing Then
' Disable events to prevent recursive triggering
Application.EnableEvents = False
' Store the address of the active cell
Dim activeCellAddress As String
activeCellAddress = ActiveCell.Address
' Sort the table based on the "Date" column in ascending order
tbl.Sort.SortFields.Clear
tbl.Sort.SortFields.Add Key:=tbl.ListColumns("Date").DataBodyRange, SortOn:=xlSortOnValues, Order:=xlAscending
tbl.Sort.Apply
' Re-enable events
Application.EnableEvents = True
' Return to the original active cell
Range(activeCellAddress).Select
End If
End Sub
Thank you
Here is the code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim tbl As ListObject
Set tbl = Me.ListObjects(1) ' Assuming your table is the first ListObject on the sheet
' Check if the changed cell is within the table
If Not Intersect(Target, tbl.ListColumns("Date").DataBodyRange) Is Nothing Then
' Disable events to prevent recursive triggering
Application.EnableEvents = False
' Store the address of the active cell
Dim activeCellAddress As String
activeCellAddress = ActiveCell.Address
' Sort the table based on the "Date" column in ascending order
tbl.Sort.SortFields.Clear
tbl.Sort.SortFields.Add Key:=tbl.ListColumns("Date").DataBodyRange, SortOn:=xlSortOnValues, Order:=xlAscending
tbl.Sort.Apply
' Re-enable events
Application.EnableEvents = True
' Return to the original active cell
Range(activeCellAddress).Select
End If
End Sub
Thank you