简体   繁体   中英

Grand total pivot table range reference for excel VBA

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.

在此处输入图像描述

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

在此处输入图像描述

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM