Excel VBA loop through pivotitems that are filtered

前端 未结 1 641
Happy的楠姐
Happy的楠姐 2021-01-24 02:49

I am new to the forum, so please indulge me if my post is incomplete.

I have a very simple pivot table with one row field, one column field, one data field and one filte

1条回答
  •  迷失自我
    2021-01-24 03:09

    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
    

    0 讨论(0)
提交回复
热议问题