DSM
DSM

Reputation: 257

How to get the range of "Total Sum" column in a pivot table? Excel VBA

Is there anyway to get the range of the total sum column from a pivot table using excel vba. The range I am referring to is in the screenshot below, highlighted yellow.

pivot table with the last grand total column highlighted; header and grand total row are not highlighted

I tried using the macro recorder in excel to see if it could help answer my question. This results in me getting this.

ActiveSheet.PivotTables("PivotTable1").PivotSelect _
    "'Sum of Unit Cost' 'Row Grand Total'", xlDataAndLabel, True

however this selects a range which is more than needed as seen in the screenshot.

both the data rows and the heading row are selected

I could do something like offsetting what is selected by 2 rows and then maybe resizing it to fit the intended range but I was wondering if there was a more straight forward way of doing this.

Upvotes: 4

Views: 2892

Answers (2)

Rodlima
Rodlima

Reputation: 11

You can use this code to select GrandTotals. It works for rows and columns in case you also need it. The final part is to remove last row (or column).

Sub SelectGrandTotal()

  Dim pt As PivotTable
  Dim rColumnTotal As Range, rRowTotal As Range
  Dim numrows As Long, numcolumns As Integer
  
  Set pt = ActiveSheet.PivotTables(1)
  
  With pt
  
    'The conditions below are checking if the GrandTotals are activated. Not really necessary in some cases.
    
    'Uncomment this block to work with Columns
    'If .ColumnGrand Then
    '  With .DataBodyRange
    '    Set rColumnTotal = .Rows(.Rows.Count)
    '    rColumnTotal.Select
    '  End With
    'End If

    If .RowGrand Then
      With .DataBodyRange
        Set rRowTotal = .Columns(.Columns.Count)
        rRowTotal.Select
        
      End With
    End If
  End With
  
    'Resizes selection and removes last Row (you can do the same for columns if necessary)
    numrows = Selection.Rows.Count
    numcolumns = Selection.Columns.Count
    Selection.Resize(numrows - 1, numcolumns).Select

End Sub

Upvotes: 1

Mathieu Guindon
Mathieu Guindon

Reputation: 71177

Try changing xlDataAndLabel to xlDataOnly; see the XlPTSelectionMode enum on docs.microsoft or find it in the Object Browser (F2) for a list of all the available members.

Upvotes: 0

Related Questions