Get the List of Visible Items from a Pivot Field using VBA

Pramod picture Pramod · Aug 1, 2016 · Viewed 8.9k times · Source

I'm using the below code to loop through a pivot field for getting the pivot items which are visible. But the pivotitem.count gives a 0 when the pivot field is in Row Label When I move this pivot field to Column Label, the code is working fine. But I NEED this Field to stay on row label.

Is there any work around for my problem?

Dim pt As PivotTable
Dim pf As PivotField
Dim pvtitem As PivotItem

Set nwSheet = Worksheets.Add
nwSheet.Activate
rw = 0

Set pt = Sheets("Reasons").PivotTables("PivotFields")
Set pf = pt.PivotFields("[Characteristics].[Reason].[Reason]")

With pf
    For i = 0 To .PivotItems.Count
        rw = rw + 1
        nwSheet.Cells(rw, 1).Value = .PivotItems.Count
    Next i
End With

Answer

Kamran Hyder picture Kamran Hyder · Aug 2, 2016

Iterating on RowFields, explicitly, can get a handle on visible Pivot Items in Row Fields. Please see if this serves the purpose:

    Set pt = Sheets("Reasons").PivotTables("PivotFields")
    Dim pf As PivotField
    For Each pf In pt.RowFields
          MsgBox pf.Name & " : " & pf.VisibleItems.Count
    Next

To iterate on Report Filter:

Dim pt As PivotTable
Dim pFilter As PivotFilter
Dim pFilters As PivotFilters
Dim pF As PivotField

Set pt = Sheets("Reasons").PivotTables("PivotFields")
'Set the first RowField as the PivotField
Set pF = pt.RowFields(1)

'Remove previous filters
pF.ClearAllFilters

'Assuming we have a RowField as 'Quarter' and DataField as 'Sum of Sale',
'we can apply a new 'ValueIsLessThan' filter for a Sum of Sale value of 12000

pt.PivotFields("Quarter").PivotFilters.Add Type:=xlValueIsLessThan, _
DataField:=pt.PivotFields("Sum of Sale"), Value1:=12000

Set pFilters = pt.PivotFields("Quarter").PivotFilters

For Each pFilter In pFilters
  MsgBox "Filter Applied On: " & pFilter.PivotField.Name & " -- Filtered values for less than : " & pFilter.Value1
Next