Updating Pivotfields from a Data Validation list across multiple Pivot Tables on Multiple sheets

Carpenter447

New Member
Joined
Mar 5, 2012
Messages
10
Hello I have an issue that i have been playing around with my self for quite sometime now. I found a code that should work but for some reason it is not working and I haven't a clue why. Any help would be appreciated.

Goal : Code that will take a drop list and modify the pivot filters on multiple pivot tables on multiple sheets simultaneously. I.e. Drop list selection is Brown; Brown is part of the Filter Colors; All subsequent pivot tables with the same Filter for colors would then switch to brown and update the data within it.

Issue : The coding works on a sample set that I ripped from contexures.com but not for my data as it stands now.

Additional Info : I am running Excel 2007, I import that data within my pivots from an OLAP cube, & even though I work with macros quite often my actual verbatim writing skills are limited.

So the code below is an adapted version of what you can find on contextures website. I want to be able change three unique Pivot Fields simultaneously. The code string is simply triplicated below with the different fields inputted. When I use the initial code from contexture.com it works but then when i change the Pivotfield nothing happens.

Code:
Sub UpdatePivotFields()
Dim ws As Worksheet
Dim pt As PivotTable
Dim pi As PivotItem
Dim strField1 As String
Dim strField2 As String
Dim strField3 As String

On Error Resume Next
Application.ScreenUpdating = False
Application.EnableEvents = False

'This sector changes strField1 or "Top Customer Name US"
strField1 = "Top Customer Name US"
    If Target.Address = Range("D2").Address Then
        For Each ws In ThisWorkbook.Worksheets
            For Each pt In ws.PivotTables
                With pt.PageFields(strField1)
                    For Each pi In .PivotItems
                        If pi.Value = Target.Value Then
                            .CurrentPage = Target.Value
                            Exit For
                        Else
                            .CurrentPage = "(All)"
                        End If
                    Next pi
                End With
            Next pt
        Next ws
    End If

'This sector changes strField2 or "_Plant"
strField2 = "_Plant"
    If Target.Address = Range("M2").Address Then
        For Each ws In ThisWorkbook.Worksheets
            For Each pt In ws.PivotTables
                With pt.PageFields(strField1)
                    For Each pi In .PivotItems
                        If pi.Value = Target.Value Then
                            .CurrentPage = Target.Value
                            Exit For
                        Else
                            .CurrentPage = "(All)"
                        End If
                    Next pi
                End With
            Next pt
        Next ws
    End If

'This sector changes strField3 or "Month"
strField3 = "Month"
    If Target.Address = Range("U2").Address Then
        For Each ws In ThisWorkbook.Worksheets
            For Each pt In ws.PivotTables
                With pt.PageFields(strField1)
                    For Each pi In .PivotItems
                        If pi.Value = Target.Value Then
                            .CurrentPage = Target.Value
                            Exit For
                        Else
                            .CurrentPage = "(All)"
                        End If
                    Next pi
                End With
            Next pt
        Next ws
    End If
End Sub
 
Hi again,

You could try the code below.
Make sure to copy it into the Sheet Code Module of the Sheet that has the 3 DV cells (don't copy it to a Standard Code Module).

...

I'm not able to test this since I don't have the OLAP data source, but the Debug.Print strings being sent to the Immediate Window seem to be working as intended.

So I tested your code and we are getting somewhere, because something actually happened this time which I am psyched about. The unfortunate part is that it didn't execute fully.

When changing the initial DV "Top US Customer" the first PVTable in your code Casefill.PivotTopLeft was changed but I think it simply cleared the filter and nothing else. The same thing happens for Casefill.Pivot when changing "_Plant" but for the Plant filter and nothing else.

To be more clear which ever DV you change ONLY the Casefill.PivotTopLeft changes and it simply clears the filter to all entries.

Great progress if you ask me but I am not sure how else we could modify to enable the true selection to be populated within the filter and secondly how to translate that to all Pivot that have the filter that was changed.

Let me know what you think. Thanks again.
 
Upvote 0

Excel Facts

Shade all formula cells
To shade all formula cells: Home, Find & Select, Formulas to select all formulas. Then apply a light fill color.
Okay - we'll call that progress. ;)

Let's repeat the step you did around Post 4 or 5 in which you manually did the process of clearing and setting the Report Filter with the macro recorder on. Perhaps something has changed since then, or I might have gotten the syntax wrong.

Just do each of the 3 fields for one PivotTable- no need to go through more than one Pivot.
 
Upvote 0
Okay - we'll call that progress. ;)

Let's repeat the step you did around Post 4 or 5 in which you manually did the process of clearing and setting the Report Filter with the macro recorder on. Perhaps something has changed since then, or I might have gotten the syntax wrong.

Just do each of the 3 fields for one PivotTable- no need to go through more than one Pivot.

Here is what I came up with let me know if this helps:

Code:
Sub SyntaxRecord()

        Sheets("ATP Cut").Select
    ActiveSheet.PivotTables("PivotTopRight1").PivotFields( _
        "[TopCustomersUS].[Top Customer Name US].[Top Customer Name US]"). _
        VisibleItemsList = Array("")
    ActiveSheet.PivotTables("PivotTopRight1").PivotFields( _
        "[Plant].[_Plant].[_Plant]").ClearAllFilters
    ActiveSheet.PivotTables("PivotTopRight1").PivotFields( _
        "[Plant].[_Plant].[_Plant]").CurrentPageName = "[Plant].[_Plant].[All Plants]"
    ActiveSheet.PivotTables("PivotTopRight1").PivotFields("[Time].[Month].[Month]") _
        .ClearAllFilters
    ActiveSheet.PivotTables("PivotTopRight1").PivotFields("[Time].[Month].[Month]") _
        .CurrentPageName = "[Time].[Month].&[2012100]"
    ActiveSheet.PivotTables("PivotTopRight1").PivotFields( _
        "[TopCustomersUS].[Top Customer Name US].[Top Customer Name US]"). _
        VisibleItemsList = Array("[TopCustomersUS].[Top Customer Name US].&[WAL-MART]")
    ActiveSheet.PivotTables("PivotTopRight1").PivotFields( _
        "[Plant].[_Plant].[_Plant]").ClearAllFilters
    ActiveSheet.PivotTables("PivotTopRight1").PivotFields( _
        "[Plant].[_Plant].[_Plant]").CurrentPageName = "[Plant].[_Plant].&[1330]"
    ActiveSheet.PivotTables("PivotTopRight1").PivotFields("[Time].[Month].[Month]") _
        .ClearAllFilters
    ActiveSheet.PivotTables("PivotTopRight1").PivotFields("[Time].[Month].[Month]") _
        .CurrentPageName = "[Time].[Month].&[2012101]"
    ActiveSheet.PivotTables("PivotTopRight1").PivotFields( _
        "[TopCustomersUS].[Top Customer Name US].[Top Customer Name US]"). _
        VisibleItemsList = Array("[TopCustomersUS].[Top Customer Name US].&[MEIJER]")
    ActiveSheet.PivotTables("PivotTopRight1").PivotFields( _
        "[Plant].[_Plant].[_Plant]").ClearAllFilters
    ActiveSheet.PivotTables("PivotTopRight1").PivotFields( _
        "[Plant].[_Plant].[_Plant]").CurrentPageName = "[Plant].[_Plant].[All Plants]"
End Sub
 
Upvote 0
That helped me spot my error. Thanks.

Try changing the line shown below....
Code:
   [COLOR="Teal"]'---Filter each PT in list using Parameters[/COLOR]
    For i = LBound(vPTNames) To UBound(vPTNames)
       [COLOR="teal"] '---for Testing[/COLOR]
        Debug.Print "Setting Sheet!PT:" & vPTNames(i) & _
                "  Field:" & sField & "   Page:" & sPage
        vPTName = Split(vPTNames(i), "!")
        Set PT = Sheets(vPTName(0)).PivotTables(vPTName(1))
        With PT.PivotFields(sField)
            .ClearAllFilters
 [B]           [COLOR="Blue"].CurrentPageName = sPage[/COLOR][/B]
        End With
    Next i
 
Upvote 0
That helped me spot my error. Thanks.

Try changing the line shown below....
Code:
   [COLOR="Teal"]'---Filter each PT in list using Parameters[/COLOR]
    For i = LBound(vPTNames) To UBound(vPTNames)
       [COLOR="teal"] '---for Testing[/COLOR]
        Debug.Print "Setting Sheet!PT:" & vPTNames(i) & _
                "  Field:" & sField & "   Page:" & sPage
        vPTName = Split(vPTNames(i), "!")
        Set PT = Sheets(vPTName(0)).PivotTables(vPTName(1))
        With PT.PivotFields(sField)
            .ClearAllFilters
 [B]           [COLOR="Blue"].CurrentPageName = sPage[/COLOR][/B]
        End With
    Next i

That did work well I am just having a couple more issues with functionality around the consistency of the results. I will outline the main ones below:

  1. Modifying the [MONTH] DV is nt connecting with the tables and I think it must be a syntax thing. I had one idea i.e. Selecting "May-12" from the DV translates to the correct value. The first blurp below is my immediate window from the DV. And, the second is when I actually change the month inside the PivotTable. I just don't know how to incorporate that in the code...

    "Do note that both blurps align in what was chosen."

    Setting Sheet!PT:Casefill!PivotTopLeft Field:[Time].[Month].[Month] Page:[Time].[Month].&[Apr-12]
    Setting Sheet!PT:Casefill!PivotTopLeft Field:[Time].[Month].[Month] Page:[Time].[Month].&[May-12]
    Setting Sheet!PT:Casefill!PivotTopLeft Field:[Time].[Month].[Month] Page:[Time].[Month].&[Dec-11]​

    Code:
        ActiveSheet.PivotTables("PivotTopRight1").PivotFields("[Time].[Month].[Month]") _
            .ClearAllFilters
        ActiveSheet.PivotTables("PivotTopRight1").PivotFields("[Time].[Month].[Month]") _
            .CurrentPageName = "[Time].[Month].&[2012100]"
        ActiveSheet.PivotTables("PivotTopRight1").PivotFields("[Time].[Month].[Month]") _
            .ClearAllFilters
        ActiveSheet.PivotTables("PivotTopRight1").PivotFields("[Time].[Month].[Month]") _
            .CurrentPageName = "[Time].[Month].&[2012101]"
        ActiveSheet.PivotTables("PivotTopRight1").PivotFields("[Time].[Month].[Month]") _
            .ClearAllFilters
        ActiveSheet.PivotTables("PivotTopRight1").PivotFields("[Time].[Month].[Month]") _
            .CurrentPageName = "[Time].[Month].&[201196]"
  2. When selecting the different incorporate all fields indicators from the DV's only the first table "PivotTopLeft" changes.

    Immediate Window
    Changing the Customer DV:
    Setting Sheet!PT:Casefill!PivotTopLeft Field:[TopCustomersUS].[Top Customer Name US].[Top Customer Name US] Page:[TopCustomersUS].[Top Customer Name US].&[Top Customer Name US]
    Or
    Setting Sheet!PT:Casefill!PivotTopLeft Field:[TopCustomersUS].[Top Customer Name US].[Top Customer Name US] Page:[TopCustomersUS].[Top Customer Name US].&[Top Customer Name US]Setting Sheet!PT:Casefill!PivotTopLeft Field:[TopCustomersUS].[Top Customer Name US].[Top Customer Name US] Page:[TopCustomersUS].[Top Customer Name US].&[All US Customers]

    VB with Manual Intervention on Pivot:
    Code:
        Sheets("Casefill").Select
        Range("B11").Select
        ActiveSheet.PivotTables("PivotTopLeft").PivotFields( _
            "[TopCustomersUS].[Top Customer Name US].[Top Customer Name US]"). _
            ClearAllFilters
        ActiveSheet.PivotTables("PivotTopLeft").PivotFields( _
            "[TopCustomersUS].[Top Customer Name US].[Top Customer Name US]"). _
            CurrentPageName = "[TopCustomersUS].[Top Customer Name US].[All US Customers]

    Immediate Window
    Changing the Plant DV:

    Setting Sheet!PT:Casefill!PivotTopLeft Field:[Plant].[_Plant].[_Plant] Page:[Plant].[_Plant].&[_Plant]
    Setting Sheet!PT:Casefill!PivotTopLeft Field:[TopCustomersUS].[Top Customer Name US].[Top Customer Name US] Page:[TopCustomersUS].[Top Customer Name US].&[Top Customer Name US]Setting Sheet!PT:Casefill!PivotTopLeft Field:[TopCustomersUS].[Top Customer Name US].[Top Customer Name US] Page:[TopCustomersUS].[Top Customer Name US].&[All US Customers]

    VB with Manual Intervention on Pivot:
    Code:
        Sheets("Casefill").Select
        ActiveSheet.PivotTables("PivotTopLeft").PivotFields("[Plant].[_Plant].[_Plant]" _
            ).ClearAllFilters
        ActiveSheet.PivotTables("PivotTopLeft").PivotFields("[Plant].[_Plant].[_Plant]" _
            ).CurrentPageName = "[Plant].[_Plant].[All Plants]"

I know this is a lot to throw back at you, please let me know when you get a chance to take a look.

As always your expert knowledge is greatly appreciated.
 
Upvote 0
Let's look at these one at a time.

For the Months, it looks like the OLAP database is coding those using the end of 2003 as a baseline.

We can add a line or function that converts your DV Text to the year-month codes.
IE. "Apr- 12" to "2012100"

Before I code that...
1. Will your dates always be after the year 2003, or do you have historical data going back later?

2. Is your DV Text strings consistently formated as "Mmm- YY"
 
Upvote 0
Assuming your dates are not earlier than 2004 and your DV formats are consistent,
try modifying this part in the Case Statements of the Worksheet_Change code....
Code:
Case sDV_Addr3
    sField = "[Time].[Month].[Month]"
    sPage = "[Time].[Month].&[" & _
        Right(Target, 2) & DateDiff("m", "12/31/2003", _
        Replace(Target, " ", "1-20")) & "]"

For your second question, it sounds like you're saying the code works for the first PT in the list, but doesn't change the others.
If only one string is getting written to the Immediate Window, then the code is probably hitting an error due to a mismatch between the code and the Pivot's name, sheetname, fieldname or page.

Try modifying the code as shown and comment out the lines shown in Green.
This should allow all the strings to be written to the Immediate Window.

Code:
    Err.Clear
    On Error GoTo CleanUp
    Application.EnableEvents = False
    
   '---Filter each PT in list using Parameters
    For i = LBound(vPTNames) To UBound(vPTNames)
        '---for Testing
        Debug.Print "Setting Sheet!PT:" & vPTNames(i) & _
                "  Field:" & sField & "   Page:" & sPage
        vPTName = Split(vPTNames(i), "!")
[COLOR="Teal"]    '    Set PT = Sheets(vPTName(0)).PivotTables(vPTName(1))[/COLOR][COLOR="Teal"]   
    '    With PT.PivotFields(sField)
    '        .ClearAllFilters
    '        .CurrentPageName = sPage
    '    End With[/COLOR]
    Next i
       
CleanUp:
    If Err.Number <> 0 Then _
        MsgBox Err.Number & "-" & Err.Description & vbCr _
            & "Failed while trying to update: " & vPTNames(i), _
            vbExclamation
    Application.EnableEvents = True
End Sub

If you can't spot a typo or other error in those strings, take away the apostrophes to let the code try to change the Pivots.
A message box should display where the code hit the error.
[Alternatively you can Step through each line of code using F8 in the VB Editor]
 
Last edited:
Upvote 0
Hello....I have used the code above to apply filters on my pivot tables (on multiple sheets/tabs) based on a data validation which is on a different tab called "Report Selection". This code works perfectly to apply the filter (i.e. - if I select Distributor 1 from the data validation on the Report Selection tab, then report filter "Distributor" is set to Distributor 1 on all the pivot tables). The issue I have is when I try to clear the filter - the filter is only removed from the first pivot table, and not the other 3 pivot tables in the workbook. Can anyone please help? This was the full code I used:

Private Sub Worksheet_Change(ByVal Target As Range)
'---When any of DV Dropdowns is changed, sets CurrentPageName
' of corresponding PivotField for all listed PivotTables.
Dim sDV_Addr1 As String, sDV_Addr2 As String, sDV_Addr3 As String
Dim sField As String, sPage As String, i As Long
Dim PT As PivotTable
Dim vPTNames As Variant, vPTName As Variant

sDV_Addr1 = "$B$11" 'Enterprise DV Cell

'---Make list of PTs to be Filtered
vPTNames = Array("Cust YoY!CustYoY", "CustRoll12!CustRoll", _
"Brand Trend!BrandTrend", "Cust-Brand Trend!CustBrand")
If Intersect(Target, Range(sDV_Addr1)) Is Nothing Or _
Target.Cells.Count > 1 Then Exit Sub

'---Set Parameters based on DV Cell changed
Select Case Target.Address
Case sDV_Addr1
sField = "[Ship To Customer].[Customer Enterprise]." & _
"[Customer Enterprise]"
sPage = "[Ship To Customer].[Customer Enterprise].&[" _
& Target & "]"
End Select

On Error GoTo CleanUp
Application.EnableEvents = False

'---Filter each PT in list using Parameters
For i = LBound(vPTNames) To UBound(vPTNames)
'---for Testing
Debug.Print "Setting Sheet!PT:" & vPTNames(i) & _
" Field:" & sField & " Page:" & sPage
vPTName = Split(vPTNames(i), "!")
Set PT = Sheets(vPTName(0)).PivotTables(vPTName(1))
With PT.PivotFields(sField)
.ClearAllFilters
.CurrentPageName = sPage
End With
Next i

CleanUp:
Application.EnableEvents = True
End Sub
 
Upvote 0
If you're manually clearing or changing the PivotTable filters for one PivotTable, the changes won't be mirrored in the other PivotTables.

If you have xl2010 and all the Pivots share the same datasource, you could use Slicers to link the PivotTables.

Otherwise, you could clear all filters in the 3 pivot tables by adding an item to your DV list that doesn't match any pivot items (for example "Clear filters").

Modify this part of the code....

Code:
With PT.PivotFields(sField)
    .ClearAllFilters
    On Error Resume Next
   .CurrentPageName = sPage
    On Error GoTo CleanUp
End With

I haven't tested this for your example, but the result should be that the filter will be cleared, then error when trying to set the page to "Clear filters", then resume.
 
Upvote 0

Forum statistics

Threads
1,221,476
Messages
6,160,058
Members
451,615
Latest member
soroosh

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