简体   繁体   English

excel VBA 的总数据透视表范围参考

[英]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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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