0
votes

I would like to simply get the value of the grand total of a pivot table. However I need this to be more dynamic than the solution found online.

enter image description here

A simple solution that I have seen online was to get the last cell found in the range of the grand total column. In this case, resulting to something like the code mentioned below.

Dim grandTotal As Range
grandTotal = Range("E65536").End(xlUp)
MsgBox grandTotal.Value

However, this would simply fail if I had some data filled in below the pivot table, in the same column. Is there a way to precisely reference the grand total value? Maybe like referencing the data range of the two grand total column and row, and find an intersect between the two to get the cell highlighted in yellow?

Edit:

What about getting the grand total for the two different data value columns

enter image description here

2

2 Answers

0
votes

Well, since it would be the most bottom right cell in your pivot table:

Set pt = Activesheet.PivotTables(1)
grandTotal = pt.DataBodyRange.Cells(pt.DataBodyRange.Cells.Count).Value
0
votes

If you need to reference different Rows or Columns Totals, this way should work well for you.

Sub SelectGrandTotal()
  Dim pt As PivotTable
  Dim rGrandTotal As Range
  
  Set pt = ActiveSheet.PivotTables(1)
  
  With pt
  
    'This condition checks if the GrandTotals are activated. Not really necessary in some cases.
    If .ColumnGrand And .RowGrand Then
      With .DataBodyRange
      
        'Add "- 1" after ".Count" if you want to move between different Totals.
        Set rGrandTotal = .Cells(.Rows.Count, .Columns.Count)
        rGrandTotal.Select
        'Print
        MsgBox (rGrandTotal)

      End With

    End If

  End With

End Sub