2012-07-13 103 views
3

當我刷新我的數據,然後使用以下代碼在透視表上執行刷新時,默認情況下會選擇新添加的項目。是否有防止這種情況,因爲這意味着我必須再次入場並取消選擇?添加刷新時的VBA默認情況下選擇了PivotItems

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 
+0

如何在'pt.PivotCache.Refresh'之前將一些代碼加載到數組/字典/集合中。然後,在'pt.PivotCacheRefresh'之後,循環遍歷這些項並取消選中它們(如果它們不在數組/字典/集合中)。 – 2012-07-13 15:41:01

回答

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 
+0

工作,非常感謝。 – shinokamparos 2012-07-17 12:04:14

相關問題