Search code examples
excelvbasubtotal

Sum/Average Rows to Table on Multiple Tabs VBA


I would like to add subtotals for either a sum or average. The tables on these tabs all have the same row lengths, and the same headers (there is a group of 8 tabs that have 3 additional columns, so I will create another loop later on the tackle those).

I'm not sure how to make the table references in the below code generic to reference whatever table is on that specific tab. This is what I have so far...any help would be greatly appreciated! Thank you!

Sub AddTotals()

Dim tablename As Range
Dim TargetSheet As Worksheet
Dim tbl As ListObject
Dim rng As Range

Worksheets("Tab Names").Activate

For Each tablename In Worksheets("Tab Names").Range("B1:B64").Cells
    Set TargetSheet = Worksheets(CStr(tablename.Value))
    Set rng = Range(TargetSheet.Range("F11"), TargetSheet.Range("F11").SpecialCells(xlLastCell))

    Range("F11").Select
    ActiveSheet.ListObjects(Active).ShowTotals = True
    Range("Table2[[#Totals],[Var %]]").Select
    ActiveSheet.ListObjects("Table2").ListColumns("Var %").TotalsCalculation = _
    xlTotalsCalculationAverage
    Range("Table2[[#Totals],[Var $]]").Select
    ActiveSheet.ListObjects("Table2").ListColumns("Var $").TotalsCalculation = _
    xlTotalsCalculationSum

Next tablename

Solution

  • If there is only one table on each sheet, the solution is relatively trivial. However, if there are multiple tables, you will need to identify the table name as well as the tab name on your Tab Names sheet. Here's the solution if each sheet has only one table.

    For Each tablename In Worksheets("Tab Names").Range("B1:B64")
        Set TargetSheet = Worksheets(CStr(tablename.Value))
        With TargetSheet.ListObjects(1)
            .ShowTotals = True
            .ListColumns("Var %").TotalsCalculation = xlTotalsCalculationAverage
            .ListColumns("Var $").TotalsCalculation = xlTotalsCalculationSum
        End With
    Next tablename
    

    I removed a lot of unnecessary range selecting in your code. Objects don't need to be selected to work with them. In fact, it will slow things down if you do.