简体   繁体   中英

VBA code in Excel with pivot tables

The data source will change often. After I refresh the pivot table, I have the following code to update the grade pivot item field. Sometimes grade 4 is available and sometimes it is not. Essentially, If grade 4 is available I want it to be selected and if it is not available then all fields can be select. For some reason when I run it, it stops on the else line. Any suggestions?

ActiveSheet.PivotTables("PivotTable1").PivotFields("Grade").ClearAllFilters

If IsError(ActiveSheet.PivotTables("PivotTable1").PivotFields("Grade").CurrentPage = "4") Then
    ActiveSheet.PivotTables("PivotTable1").PivotFields("Grade").CurrentPage = _
    "(All)"    
Else  
    ActiveSheet.PivotTables("PivotTable1").PivotFields("Grade").CurrentPage = "4"           
End If

You can't trap the PivotField("Grade").CurrentPage error with IsError .

Try the code below:

ActiveSheet.PivotTables("PivotTable1").PivotFields("Grade").ClearAllFilters

On Error Resume Next
ActiveSheet.PivotTables("PivotTable1").PivotFields("Grade").CurrentPage = "4"

If Err.Number <> 0 Then
     ActiveSheet.PivotTables("PivotTable1").PivotFields("Grade").CurrentPage = _
    "(All)"
    On Error GoTo 0
End If

Note : you could clean up your code if you use With statements. In your code, you could use With ActiveSheet.PivotTables("PivotTable1").PivotFields("Grade")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM