Excel 默认情况下,将选择刷新时的VBA添加的数据透视项

Excel 默认情况下,将选择刷新时的VBA添加的数据透视项,excel,pivotitem,vba,Excel,Pivotitem,Vba,当我刷新数据,然后使用以下代码刷新数据透视表时,默认情况下会选择新添加的项。因为这意味着我必须再次进入并取消选择,所以是否有其他方法可以防止这种情况发生 Dim pt As PivotTable Dim pf As PivotField For Each pt In Worksheets("Summary").PivotTables pt.PivotCache.MissingItemsLimit = xlMissingItemsNone pt.Pivot

当我刷新数据,然后使用以下代码刷新数据透视表时,默认情况下会选择新添加的项。因为这意味着我必须再次进入并取消选择,所以是否有其他方法可以防止这种情况发生

    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

根据我上面的评论,类似的方法应该可以奏效。如果需要检查很多透视字段,则可以创建一些函数以使其更容易或更高效

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

pt.PivotCache.Refresh
之前,将一些代码加载到所有选定项中的数组/字典/集合中。然后,在
pt.PivotCacheRefresh
之后,循环遍历这些项,如果它们不在数组/字典/集合中,则取消选中它们。