Search code examples
excelpivotitemvba

VBA on refresh added PivotItems are selected by default


When I refresh my data and then do a refresh on my pivot table using the following code, new added items are selected by default. Is there away to prevent this as it means I have to go in again and deselect?

    Dim pt As PivotTable
    Dim pf As PivotField
    For Each pt In Worksheets("Summary").PivotTables

    pt.PivotCache.MissingItemsLimit = xlMissingItemsNone
    pt.PivotCache.Refresh

    For Each pf In pt.PivotFields
       pf.AutoSort xlAscending, pf.Name
    Next pf
    Next pt

    Set pf = Nothing
    Set pt = Nothing

Solution

  • Based on my comment above, something like this should work. If you have a lot of pivot fields you need to check, you could probably create some functions to make it easier or more efficient.

    Sub pt()
    
    
    Dim pt As PivotTable, pf As PivotField, pi As PivotItem
    Dim dict As Dictionary 'requires reference to Microsoft Scripting Runtime
    
    For Each pt In Worksheets("Summary").PivotTables
    
        pt.PivotCache.MissingItemsLimit = xlMissingItemsNone
    
        Set dict = New Dictionary
    
        ' you will need to loop through each Fields PivotItem Collection separately 
        For Each pi In pt.PivotFields("myPivotField").PivotItems
            dict.Add pi.Name, 1
        Next
    
        pt.PivotCache.Refresh
    
       'again, you will need to loop through each one separately to check
        For Each pi In pt.PivotFields("myPivotField").PivotItems
            If dict.Exists(pi.Name) Then Else: pi.Visible = False
        Next
    
        For Each pf In pt.PivotFields
           pf.AutoSort xlAscending, pf.Name
        Next pf
    
    Next pt
    
    Set pf = Nothing
    Set pt = Nothing
    
    End Sub