Excel VBA识别在Excel界面中可见的数据透视项目

时间:2018-10-25 20:04:00

标签: excel vba excel-vba pivot-table

我的数据透视表包含一个过滤器,用于过滤带有"Days_Outstnading_Category"=">180 days"的项目。

enter image description here

过滤后,我的行字段"Operating Units"仅在excel界面中显示2个项目“ US”和“ India”,尽管“ Operating Units”中的所有项目都具有Visible=True,但实际上只有在excel界面中实际可见2个项目。

我想知道如何识别这两个项目,因为If pivotItem.Visible=True现在将无法使用。

最终,我想迭代并选择出现在excel界面(A5:A12,A14:A27,B5,B6:B9等)中的每个项目的LabelRange,并对每个范围进行一些格式更改。而且下面的代码带来了一个错误,其中找不到labelrange。

> For Each ptRowField In pt.RowFields
>      For Each ptRowFieldItem In ptRowField.PivotItems
>          If ptRowFieldItem.Visible = True Then
>              Call SetOusideBorder(ptRowFieldItem.LabelRange)
>          End If
>      Next ptRowFieldItem 
> Next ptRowField

1 个答案:

答案 0 :(得分:0)

我使用过的最简单的方法是在数据透视表中获取包含行标签的列。

在我的示例数据集中,我有7种颜色:红色,橙色,黄色,绿色,蓝色,靛蓝和紫色。我已经设置了数据并创建了数据透视表,然后对其进行了过滤,因此仅显示三种颜色:

enter image description here

因此,您可以使用.RowRange属性访问数据透视表中行标签的列。一旦有了,就可以降低单元格的大小:

Option Explicit

Public Sub ListVisibleItems()
    Dim thisPivot As PivotTable
    Set thisPivot = ActiveSheet.PivotTables(1)

    Dim rowField As PivotField
    Set rowField = thisPivot.RowFields("Color")

    Dim theseRows As Range
    Set theseRows = thisPivot.RowRange

    Dim i As Long
    '--- start at 2 to skip the "Row Labels" and end at Count-1
    '    to skip the "Grand Total" 
    For i = 2 To theseRows.Count - 1
        Debug.Print theseRows.Cells(i, 1) & " is visible"
    Next i
End Sub
  

编辑:更新示例代码以解析OP的示例数据

Option Explicit

Public Sub ListVisibleItems()
    Dim thisPivot As PivotTable
    Set thisPivot = ActiveSheet.PivotTables(1)

    Dim rowField As PivotField
    Set rowField = thisPivot.RowFields("Color")

    Dim theseRows As Range
    Set theseRows = thisPivot.RowRange

    Dim i As Long
    '--- start at 2 to skip the "Operating Units" and end at Count-1
    '    to skip the "Grand Total" 
    For i = 2 To theseRows.Count - 1
        '--- check to make sure the row is not empty and that
        '    the value does NOT have the word "Total"
        If Len(theseRows.Cells(i, 1)) > 0 Then
            If Not theseRows.Cells(i, 1) Like "*Total" Then
                Debug.Print theseRows.Cells(i, 1) & " is visible"
                '--- you can use this result as the field name
                '    to select and format the data area
            End If
        End If
    Next i
End Sub