2017-02-20 82 views
3

我想通過循環表中的所有數據透視表並刪除它們中具有相同名稱的所有值字段:「Total Net Spend」和「%Split」(請參見圖片參考)。通過數據透視表循環並刪除相同的值

enter image description here

我想下面的代碼,但它只能通過他們都在第一樞軸工作,不會循環。如何編輯代碼,以便它將刪除工作表中所有透視表上的「總淨支出」和「%分割」列?

Sub Loop_Pivots() 

Dim PT As PivotTable, PTField As PivotField 

Set PT = Sheets("Sheet1").PivotTables("Pivot1") 
With PT 
    .ManualUpdate = True 
    For Each PTField In .DataFields 
     PTField.Orientation = xlHidden 
    Next PTField 
    .ManualUpdate = False 
End With 
Set PT = Nothing 

End Sub 

回答

0

要遍歷PivotTables嘗試另一個foreach環這樣

Sub Loop_Pivots() 

    Dim PT As PivotTable, PTField As PivotField 
    For Each PT In Sheets("Sheet1").PivotTables 
     With PT 
      .ManualUpdate = True 
      For Each PTField In .DataFields 
       PTField.Orientation = xlHidden 
      Next PTField 
      .ManualUpdate = False 
     End With 
    Next PT 
    Set PT = Nothing 
End Sub 
+1

只是嘗試,但一個錯誤彈出說:無法設置PivotField類的方向屬性... – Andrea

0

嘗試下面的代碼:

Option Explicit 

Sub Loop_Pivots() 

Dim PT   As PivotTable 
Dim PTField  As PivotField 

For Each PT In Sheets("Sheet1").PivotTables 

    With PT 
     .ManualUpdate = True 
     For Each PTField In .PivotFields '<-- loop through all pivot fields 
      Select Case PTField.Name 
       Case "Total Net Spend", "% Split" '<-- if Field Name equals on of the 2 in this case 
        PTField.Orientation = xlHidden 
      End Select 
     Next PTField 
     .ManualUpdate = False 
    End With 
    Set PT = Nothing 
Next PT 

End Sub 
+0

感謝您的幫助,但此代碼沒有任何反應......通過原始代碼,我能夠擺脫「總淨支出「和」%分割「,但它不會循環通過其餘的樞軸... – Andrea

+0

@Andrea奇怪,爲我工作。它會返回一個錯誤嗎? –

+0

沒有錯誤。它只是不會做任何事情...... – Andrea

相關問題