Share via

Using multiple VBA codes within a single worksheet

Anonymous
2024-05-29T22:02:51+00:00

I have four tables in a worksheet that I am attempting to auto refresh sorting. I used the code below to make this work for one table in the worksheet. Now I want to do the same thing for the other three tables. How do I do this?

Private Sub Worksheet_Change(ByVal Target As Range)

Dim SalesTable As ListObject

Dim SortCol As Range

Set SalesTable = ActiveSheet.ListObjects("Quarter1")

Set SortCol = Range("Quarter1[Subsidiary]")

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

Microsoft 365 and Office | Excel | For business | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

1 answer

Sort by: Most helpful
  1. Anonymous
    2024-05-30T01:37:37+00:00

    Could you share a test workbook?

    You may add all the code into one like this one.

    =======================

    Private Sub Worksheet_Change(ByVal Target As Range)

    Dim SalesTable As ListObject

    Dim SortCol As Range

    Set SalesTable = ActiveSheet.ListObjects("Quarter1")

    Set SortCol = Range("Quarter1[Subsidiary]")

    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

    Set SalesTable2 = ActiveSheet.ListObjects("Quarter2")

    Set SortCol2 = Range("Quarter2[Subsidiary]")

    If Not Intersect(Target, SortCol2) Is Nothing Then

    With SalesTable.Sort

    .SortFields.Clear

    .SortFields.Add Key:=SortCol, Order:=xlAscending

    .Header = xlYes

    .Apply

    End With

    End If

    Set SalesTable3 = ActiveSheet.ListObjects("Quarter3")

    Set SortCol3 = Range("Quarter3[Subsidiary]")

    If Not Intersect(Target, SortCol3) Is Nothing Then

    With SalesTable.Sort

    .SortFields.Clear

    .SortFields.Add Key:=SortCol, Order:=xlAscending

    .Header = xlYes

    .Apply

    End With

    End If

    Set SalesTable4= ActiveSheet.ListObjects("Quarter4")

    Set SortCol4 = Range("Quarter4[Subsidiary]")

    If Not Intersect(Target, SortCol4) Is Nothing Then

    With SalesTable.Sort

    .SortFields.Clear

    .SortFields.Add Key:=SortCol, Order:=xlAscending

    .Header = xlYes

    .Apply

    End With

    End If

    End Sub

    Was this answer helpful?

    0 comments No comments