VBA macro: Loop through pivot columns

gio123bg

Active Member
Joined
Feb 14, 2004
Messages
255
Hi All,
I have the necessity to check the values in two columns of two pivot tables. The pivot tables have the same layout. Is it possible to have an example of VBA code? I tried to find it but without success.

Any help will be well appreciated.

Thanks in advance for your kind support.

Regards,

Giovanni
 

Excel Facts

Do you hate GETPIVOTDATA?
Prevent GETPIVOTDATA. Select inside a PivotTable. In the Analyze tab of the ribbon, open the dropown next to Options and turn it off
Hi Giovanni,

Here is an example showing how to step through all PivotTables in a specified Worksheet and process each value in two named datafields.

Note there isn't any error handling, so you will get an unhandled error if both datafields aren't found in each Pivot Table.

Code:
Sub PT_Values()
    Dim PT As PivotTable
    Dim i As Long
    Dim c As Range
    Dim varFields As Variant
    
    varFields = Split("Sum of Sales;Count of Stores", ";")
        
    For Each PT In Sheets("Sheet1").PivotTables
        For i = LBound(varFields) To UBound(varFields)
            With PT.DataFields(varFields(i))
                For Each c In PT.DataBodyRange.Resize(, 1) _
                        .Offset(0, .Position - 1)
                    'for testing demo only....
                    MsgBox PT.Name & "> " & varFields(i) & "> " & c.Value
                Next
            End With
        Next i
    Next PT
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,918
Messages
6,122,249
Members
449,075
Latest member
staticfluids

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top