过滤数据透视表中的字段并获取可见值

时间:2012-10-23 11:38:21

标签: excel-vba vba excel

考虑我有这样的数据

Company     Department  Size
=================================
HCL         BFS         50
HCL         Insurance   60
CTS         BFS         20
CTS         Insurance   30
CTS         Healthcare  50

Pivot without any filter

在这里,我想过滤掉BFS并找到每个公司级别的剩余总数,如下所示

案例1:Pivot With filter - after removing BFS as the department using filter

 Company    Department  Total
 CTS    Healthcare  50
        Insurance   30
 CTS Total           80
 HCL    Insurance   60
 HCL Total           60
 Grand Total        140

案例2:Pivot table with only single Company after filtering of the Department

 CTS    Healthcare  50
 CTS Total           50
 Grand Total        50

尝试使用相同的

宏代码
 For Each V In Set visiblePivot = ActiveSheet.PivotTables("PivotTable2") _
           .PivotFields("Company").VisibleItems
 str = (str & "," & V)
 Next V
 MsgBox str

那么在运行宏时我得到什么输出?

编辑:

对于案例1,我得到输出为HCL和CTS

 ---------------------------
 Microsoft Excel
 ---------------------------
 ,CTS,HCL
 ---------------------------
 OK   
 ---------------------------

对于案例2,我得到输出为HCL和CTS。

 ---------------------------
 Microsoft Excel
 ---------------------------
 ,CTS,HCL
 ---------------------------
 OK   
 ---------------------------

那么我期望什么作为输出?

对于案例1,我希望输出为HCL和CTS

 ---------------------------
 Microsoft Excel
 ---------------------------
 ,CTS,HCL
 ---------------------------
 OK   
 ---------------------------

对于案例2,我希望输出仅为CTS。

 ---------------------------
 Microsoft Excel
 ---------------------------
 ,CTS
 ---------------------------
 OK   
 ---------------------------

总结

如果Company中的字段已被过滤,请告诉我如何使用可见Department名称的宏

1 个答案:

答案 0 :(得分:0)

以下是我最终用于在数据透视表中查找过滤数据的代码

Sub getVisibleFields()
    ' this will return all the rows that are visible in the 
    'pivot table. Even the subtotal rows
    Set visibleCompany = ActiveSheet.PivotTables("PivotTable2") _
               .PivotFields("Company").DataRange
    For Each V In visibleCompany
        ' different values can be checked to filter out unwanted data
        'to find data like "CTS Total           80"
        If InStrRev(visibleCompany(i + 1), " Total") > 0 Then
            MsgBox ("Total is " & visibleCompany(i + 1)
        End If
        str = (str & "," & V)
    Next V
    MsgBox str
 End Sub