问题
I have an Excel workbook containing multiple worksheets with multiple pivot tables on each worksheet. I'm attempting to loop through every pivot table and change its 'Report Function' filter to a user-specified value selected from a List Box. All the pivot tables have the "Report Function" filter.
I have around 50 pivot tables, and the code successfully changes the filters for all but around 8 pivots. Those 8 pivot tables' filters don't change; instead, the error "Error 1004: Unable to get the CurrentPage property of the PivotField class" is returned.
wHY is this code returning this error for a small number of pivot tables?
Strangely, it seems to be the exact same pivot tables that are returning this error.
Sub ChangePivotFilter(str As String)
Dim ws As Excel.Worksheet
Dim aWB As Excel.Workbook
Dim myPivot As Excel.PivotTable
Dim myPivotField As Excel.PivotField
Set aWB = ActiveWorkbook
For Each ws In aWB.Worksheets
For Each myPivot In ws.PivotTables
Set myPivotField = Nothing
On Error Resume Next
Set myPivotField = myPivot.PivotFields("Report Function")
myPivotField.CurrentPage = str
Next myPivot
Next ws
End Sub
Any help is much appreciated!
回答1:
Assigning to, or reading from CurrentPage will fail if the PivotField isn't physically in "page" (i.e. a "Filter") on its PivotTable:
You can programmatically send a PivotField to "page" by setting its Orientation property to xlPageField, as follows:
myPivotField.Orientation = xlPageField
来源:https://stackoverflow.com/questions/45203856/vba-error-1004-unable-to-get-the-currentpage-property-of-the-pivotfield-class