Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speed up pivot table filtering VBA code

I have a pivot table with a pivot field and contain many items. I've VBA code logic to decide if the pivot value should be visible or not. The problem is excel recalculates pivot table for each field shown or hidden which makes it very slow. I would like something where it recalculates only once, after all the values are set. I tried using Application.Calculation = xlCalculationManual but it didnt help.

vba code that I am using is something like this

For i = 1 To oPivotField.PivotItems.Count
    If (oPivotField.PivotItems(i).Name = "TestCondition") Then
        oPivotField.PivotItems(i).Visible = True   'Recalulates pivot table
    Else
        oPivotField.PivotItems(i).Visible = False 'Recalulates pivot table
    End If
Next

I am to do this manually by uncheck the "show all" box and re-check for the fields I want visible. This cause Excel to recalculate once and show only the pivot items I want visible. I would like to do same thing via VBA code.

I even tried using

Application.ScreenUpdating = False
Application.DisplayAlerts = False

but didn't work.

like image 389
Ankit Avatar asked Apr 18 '09 23:04

Ankit


People also ask

How do I quickly filter a pivot table?

In the PivotTable, select one or more items in the field that you want to filter by selection. Right-click an item in the selection, and then click Filter.

What is the fastest way to select multiple filter items in a pivot table?

Choosing multiple items from a filterAt the bottom of the Filters drop-down menu is a check box labeled Select Multiple Items. If you select it, Excel adds a check box next to each item in the drop-down menu. This enables you to select multiple items from the list.


2 Answers

Oh! I just solved that one:

At the beginning of your code, turn off the auto-update like this:

PivotTable.ManualUpdate = True

And then at the end of the code, turn it back on:

ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh

I found this thread searching for help writing code that determines if a PivotTable value should be visible. What is behind your oPivotField? That's the part I'm missing!

like image 186
Michelle Avatar answered Nov 08 '22 10:11

Michelle


PivotTable objects have a ManualUpdate property which might be what you are looking for.

See http://www.ozgrid.com/VBA/hide-pivot-fields.htm for some related code

like image 24
barrowc Avatar answered Nov 08 '22 11:11

barrowc