[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Excel VBA Multi select values in pivot page filter

Posted on 2011-04-21
8
Medium Priority
?
12,851 Views
Last Modified: 2012-05-11
I currently have a macro that performs a pivot selection based on defined criteria, updates a report with the filtered results, and then copies the report data into another workbook and saves each file .  This process is completed for approximately 22 files.  The problem I’m running into now is that I need to be able to select multiple values (40309, 40308, 30498, 30496) for Coid in the page/report filter.  I’ve tried several different statements, performing loops, etc. and none seem to do the multi select.  When doing the recorder I notice that it sets all the values for Coid to .visible=false but I’m unable to use this code as there can be new values added each month.  Here is a sample of my current code.  Is there a way in my Call Pvt_selection to include all 4 selections or using a loop to capture and to allow for values to fall in?  Code attached.


Sub GetFile()
   Call Pvt_selection(filname, "CONSOL - CALIFORNIA", "(All)", "(All)", "HMOG", "(All)")
   Call copy_values(filname, "CA", "HMO")

    Call Pvt_selection(filname, "CONSOL - ARIZONA", "(All)", "(All)", "RPPO", "(All)", "(All)")
    'Call copy_values(filname, "AZ", "RPPO")

    ActiveWindow.Close
    
    
End Sub

Sub Pvt_selection(fname As String, cm As String, bm As String, cf As String, prod As String, sp As String, cd As String)

   Windows(fname).Activate
   Application.Run "'" & fname & "'" & "!GoToPivot"
   'Sheets("pivot").Activate
   ActiveSheet.PivotTables("PivotTable1").PivotFields("Consolidated Market").CurrentPage _
           = cm
   ActiveSheet.PivotTables("PivotTable1").PivotFields("Base Market").CurrentPage _
           = bm
   ActiveSheet.PivotTables("PivotTable1").PivotFields("CMPLT_FACT_CD").CurrentPage _
           = cf
   ActiveSheet.PivotTables("PivotTable1").PivotFields("Product").CurrentPage _
           = prod
   ActiveSheet.PivotTables("PivotTable1").PivotFields("CO_SUBTYPE").CurrentPage _
           = sp
    ActiveSheet.PivotTables("PivotTable1").PivotFields("Coid").CurrentPage _           = cd

Open in new window

0
Comment
Question by:cntrygrl
  • 6
7 Comments
 
LVL 42

Expert Comment

by:dlmille
ID: 35463760
Perhaps this example will work, which demonstrates one way to make multiple pagefield selections.  If you hit the macro button, the app will select a State, Territory, and Director on this fictitious pivot table.


 
Sub UpdateFiltersAndPivots()
Dim ws As Worksheet
Dim pt As PivotTable
Dim pi As PivotItem
Dim pf As Variant

Application.ScreenUpdating = False

    'Make a selection change on a Pivot Table's Pivot Field to a new Pivot Item
    Set pt = Sheets("Pivot Data Table").PivotTables(1)
    
    'Change Territory to Houston
    'First, set the 3 levels to (ALL) just in case - to ensure a match

    For Each pf In pt.PageFields
        pf.CurrentPage = "(ALL)"
    Next pf
    
    'Now, set the PivotItem to focus on Houston on the Territory Pagefield
    
    For Each pf In pt.PageFields
        With pf
            Select Case .Name
                Case "State":
                    .CurrentPage = "Arkansas"
                Case "Territory":
                    .CurrentPage = "Little Rock"
                Case "Director":
                    .CurrentPage = "Carl"
                Case Else
                    'do nothing
            End Select
        End With
    Next pf
                
End Sub

Open in new window


See attached demo file,

Enjoy!

Dave
PlayingWithPivots-example-r1.xls
0
 
LVL 42

Expert Comment

by:dlmille
ID: 35463780
Your approach - see alternative coding - should work as well:

 
Sub UpdateFiltersAndPivots_Version2()
Dim ws As Worksheet
Dim pt As PivotTable
Dim pi As PivotItem
Dim pf As Variant

Application.ScreenUpdating = False

    'Make a selection change on a Pivot Table's Pivot Field to a new Pivot Item
    Set pt = Sheets("Pivot Data Table").PivotTables(1)
    
    'Change Territory to Houston
    'First, set the 3 levels to (ALL) just in case - to ensure a match

    For Each pf In pt.PageFields
        pf.CurrentPage = "(ALL)"
    Next pf
    
    'Now, set the PivotItem to focus on Houston on the Territory Pagefield
    
    pt.PageFields("State").CurrentPage = "Arkansas"
    pt.PageFields("Territory").CurrentPage = "Little Rock"
    pt.PageFields("Director").CurrentPage = "Carl"
                
End Sub

Open in new window


Note, however, the code provided resets all pagefields to "(ALL)" before proceeding.  In addition, there's a presumption that the value being searched actually has data where the .CurrentPage is being selected.

You can test for this, before making the selection, by looping through all the pivot items, first.

That example is forthcoming on the next post.

Dave
PlayingWithPivots-example-r2.xls
0
 

Author Comment

by:cntrygrl
ID: 35463857
Thank you Dave.

Is there a way to code for multiple values.  For example Territory Little Rock and Arkansas?
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 42

Assisted Solution

by:dlmille
dlmille earned 2000 total points
ID: 35463858
>>by looping through all the pivot items, first.

Scratch that.

Note, the first example I posted, loops through all the page fields and once found, does the selection.  You can use similar code and "flag" yourself if one of the pages doesn't exist as the data didn't support that combination.

Finally, setting everything to "(ALL)" before proceeding may help you immediately, as there's no indicate from your code what the initial state of the pivot table is, so your change of a pivot field may have no corresponding result, as another filter has yet to be converted to "(ALL)"

Please advise if this helps.  If further assistance is needed, please provide a brief fictitious sample, as it makes it easier on me, versus "inventing" data to demonstrate something that matches more closely to what you MIGHT have.

Cheers,

Dave
0
 
LVL 42

Expert Comment

by:dlmille
ID: 35463860
>>Is there a way to code for multiple values.  For example Territory Little Rock and Arkansas?

Ah - yes.  Example coming

Dave
0
 
LVL 42

Expert Comment

by:dlmille
ID: 35463864
One moment - the example I gave does allow for multiple values - one value for each pagefield.

Do you mean multiple values like Texas and Arkansas?

That example, coming

Dave
0
 
LVL 42

Accepted Solution

by:
dlmille earned 2000 total points
ID: 35463947
Here's a modification to the routine, and what it does it navigate to the right pagefield to make the change, then searches for pivotitems NOT wanted and makes them not visible (remember all are visible with the "(ALL)" setup...

 
Sub UpdateFiltersAndPivots_Version3()
Dim ws As Worksheet
Dim pt As PivotTable
Dim pi As PivotItem
Dim pf As Variant
Dim ArrayofStatestoInclude(2) As String
Dim i As Integer, found As Boolean

    ArrayofStatestoInclude(0) = "Arkansas"
    ArrayofStatestoInclude(1) = "Texas"
    
Application.ScreenUpdating = False

    'Make a selection change on a Pivot Table's Pivot Field to a new Pivot Item
    Set pt = Sheets("Pivot Data Table").PivotTables(1)
    
    'Change Territory to Houston
    'First, set the 3 levels to (ALL) just in case - to ensure a match

    For Each pf In pt.PageFields
        pf.CurrentPage = "(ALL)"
    Next pf
    
    'Now, set the PivotItem to focus on Houston on the Territory Pagefield
    
    For Each pf In pt.PageFields
    
        If pf.Name = "State" Then
            For Each pi In pf.PivotItems
                With pi
                    For i = 0 To UBound(ArrayofStatestoInclude)
                        If pi.Name = ArrayofStatestoInclude(i) Then found = True
                    Next i
                    If Not found Then
                        pi.Visible = False
                    End If
                End With
            Next pi
        End If
    Next pf
                
End Sub

Open in new window


Of course, you'll want to incorporate this as needed in your subroutine, but the goal here is to demonstrate an approach with dummy data.

Note, I initialize a variable of string array ArrayofStatesToInclude() with Texas and Arkansas - similar to what you'll want to pass to your subroutine - what to select, as opposed to what to not select - that way when your data changes, you're still deselecting the correct items.

See demo file & enjoy!

Dave
PlayingWithPivots-example-r3.xls
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Freeze panes is an option within all variants of Excel to enable parts of a sheet to remain stationary when the cursor is in another part of the sheet. This is a very useful feature which is overlooked or under used.
Excel can be a tricky bit of software to get your head around. Whilst you’ll be able to eventually get to grips with the basic understanding of how to get by, there are a few Excel tips that not everybody will even know about let alone know how to d…
This Micro Tutorial will demonstrate on a Mac how to change the sort order for chart legend values and decrpyt the intimidating chart menu.
This Micro Tutorial will demonstrate how to create pivot charts out of a data set. I also added a drop-down menu which allows to choose from different categories in the data set and the chart will automatically update.

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question