Excel VBA loop through pivotitems that are filtered

时光总嘲笑我的痴心妄想 提交于 2019-12-02 04:44:07

As you already found out about the visibility of PivotItems:

If you filter a PivotTable, then some of the PivotItems of your RowFields or ColumnFields are optically visible or not,
but VBA still returns each PivotField.PivotItem as Visible.

Also PivotField.VisibleItems.Count always remains the maximum.


The remaining "really" visible PivotItems can be addressed by PivotLine.PivotLineCell.PivotItem of each pivot-axis.

LineType distingushes between regular, blank, subtotal and grandtotal lines.

showstring = ""
For rowItemNo = 1 To pvt.PivotRowAxis.PivotLines.Count
    If pvt.PivotRowAxis.PivotLines(rowItemNo).LineType = xlPivotLineRegular Then
        For colItemNo = 1 To pvt.PivotColumnAxis.PivotLines.Count
            If pvt.PivotColumnAxis.PivotLines(colItemNo).LineType = xlPivotLineRegular Then
                showstring = showstring & _
                pvt.PivotRowAxis.PivotLines(rowItemNo).PivotLineCells(1).PivotItem.Name & ":" & _
                pvt.PivotColumnAxis.PivotLines(colItemNo).PivotLineCells(1).PivotItem.Name & _
                " = " & pvt.DataBodyRange.Cells(rowItemNo, colItemNo).Value & vbCrLf
            End If
        Next colItemNo
    End If
Next rowItemNo
MsgBox showstring

If you have more than one column or row field, then PivotLineCells() can distinguish them.


... or you loop over the DataRange of each PivotField to catch the items in visible cells of a simple pivot table:

For rowFldNo = 1 To pvt.RowFields.Count
    For colFldNo = 1 To pvt.ColumnFields.Count
        For rowItemNo = 1 To pvt.RowFields(rowFldNo).DataRange.Rows.Count
            For colItemNo = 1 To pvt.ColumnFields(colFldNo).DataRange.Columns.Count
                showstring = showstring & ...
            Next colItemNo
        Next rowItemNo
    Next colFldNo
Next rowFldNo
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!