Hello Jerry,
I was looking for a code to change the filters in a pivot table with a dynamic named range and tried your code below but I can't get it working. Can you help me out? I'm not so good in VBA and can only inmagine what is happening when reading the code and try all the time if it's working.
The changes I made in the sub for the named ranges are the following:
Sub Filter_ItemListInRange2()
Filter_PivotField _
pvtField:=Sheets("bewerk").PivotTables("Draaitabel1").PivotFields("Bewerkingscode"), _
varItemList:=Application.Transpose(Sheets("Lijsten").Range("Assembly"))
End Sub
It ends up with an error Trying to process item: 403
My pivot table is on the sheet "bewerk", the pivot table is called "Draaitabel1" The field I want to filter is called "Bewerkingscode" and the named range is on the sheet "Lijsten" and is called eg. "Assembly"
I'm working with Excel 2007 and windows 7.
Thank you in advance.
Ralf
Private Function Filter_PivotField(pvtField As PivotField, _
varItemList As Variant)
Dim strItem1 As String
Dim i As Long
On Error GoTo ErrorHandler:
Application.ScreenUpdating = False
strItem1 = varItemList(LBound(varItemList))
With pvtField
.PivotItems(strItem1).Visible = True
For i = 1 To .PivotItems.Count
If .PivotItems(i) <> strItem1 And _
.PivotItems(i).Visible = True Then
.PivotItems(i).Visible = False
End If
Next i
For i = LBound(varItemList) + 1 To UBound(varItemList)
.PivotItems(varItemList(i)).Visible = True
Next i
End With
Exit Function
ErrorHandler:
MsgBox "Error while trying to process item: " & varItemList(i)
End Function
[/code]
Below are two examples of how to call the function.
The first uses a hard-coded array for the items.
Rich (BB code):
Sub Filter_ItemListInCode()
Filter_PivotField _
pvtField:=Sheets("Sheet1").PivotTables("PivotTable1").PivotFields("SalesRep"), _
varItemList:=Array("Adams", "Baker", "Clark")
End Sub
The second example gets the Item list from a named range.
Rich (BB code):
Sub Filter_ItemListInRange()
Filter_PivotField _
pvtField:=Sheets("Sheet1").PivotTables("PivotTable1").PivotFields("SalesRep"), _
varItemList:=Application.Transpose(Sheets("Sheet2").Range("SalesRepsToShow"))
End Sub
A Dynamic Range is the most flexible if you are going to have a variable number of Sales Reps that you want to display. In order to work with this code the Dynamic Range has to be non-volatile.
Hope this helps![/QUOTE]