3

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

    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
4

1 回答 1

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
于 2012-07-13T15:59:20.853 回答