简体   繁体   English

如何获取数据透视表中“总和”列的范围? Excel VBA

[英]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.无论如何,是否可以使用 excel vba 从数据透视表中获取总和列的范围。 The range I am referring to is in the screenshot below, highlighted yellow.我指的范围在下面的屏幕截图中,突出显示为黄色。

突出显示最后一个总计列的数据透视表;标题和总计行未突出显示

I tried using the macro recorder in excel to see if it could help answer my question.我尝试在 excel 中使用宏记录器,看看它是否可以帮助回答我的问题。 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.但是,如屏幕截图所示,这会选择一个超出需要的范围。

数据行和标题行都被选中

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.我可以做一些事情,比如抵消 2 行选择的内容,然后调整它的大小以适应预期的范围,但我想知道是否有更直接的方法来做到这一点。

You can use this code to select GrandTotals.您可以使用此代码来选择 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

Try changing xlDataAndLabel to xlDataOnly ;尝试将xlDataAndLabel更改为xlDataOnly see the XlPTSelectionMode enum on docs.microsoft or find it in the Object Browser ( F2 ) for a list of all the available members.请参阅 docs.microsoft 上的XlPTSelectionMode枚举或在对象浏览器( F2 ) 中找到它以获取所有可用成员的列表。

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

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