默认情况下会选择VBA on refresh added PivotItems

时间:2012-07-13 15:03:22

标签: excel-vba pivotitem vba excel

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

    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

1 个答案:

答案 0 :(得分:0)

根据我上面的评论,这样的事情应该有效。如果您需要检查很多透视字段,则可以创建一些函数以使其更容易或更有效。

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