2017-03-21 82 views
0

我在工作簿中有2個數據透視表,我有以下代碼來動態更改數據源並刷新數據透視表。代碼運行良好,因爲它循環遍歷第一個循環並刷新第一個數據透視表。然而,當循環第二透視表,代碼崩潰在pt.ChangePitvotCache一個錯誤:運行時錯誤'5':無效的porcedure調用或參數

Run-time error = '5': invalid procedure call or argument"

有誰能夠儘快我有超過1 Pivot-幫助爲什麼這不工作代碼中的表?

Dim ws As Worksheet 
Dim pvtCache As PivotCache 
Dim pt As PivotTable 
Dim newRange As String 

Set DataSource = DataSht.Range("A1", DataSht.Range("A1").End(xlToRight).End(xlDown)) 

newRange = DataSht.Name & "!" & DataSource.Address(ReferenceStyle:=xlR1C1) 

Set pvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=newRange) 

For Each ws In ActiveWorkbook.Worksheets 
    For Each pt In ws.PivotTables 
     pt.ChangePivotCache pvtCache 
     pt.RefreshTable 
    Next pt 
Next ws 

回答

0

你需要「重置」 pvtCache將其設置爲第一PivotTable後。

所以你需要SetpvtCache和「重置」它在For Each pt In ws.PivotTables循環內。

嘗試下面的代碼:

For Each ws In ActiveWorkbook.Worksheets 
    For Each pt In ws.PivotTables 
     Set pvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=newRange) 
     pt.ChangePivotCache pvtCache 
     pt.RefreshTable 
     Set pvtCache = Nothing 
    Next pt 
Next ws 
+0

感謝Shai,您的建議很有效,但只有在第二個PT不與第一個PT共享PivotCache的情況下。我現在在一張新紙上添加了一個克隆的PT,現在代碼在第一個For Each pt在ws.PivotTables循環中給出了這個錯誤... – Mike

+0

實際上它也適用於這種情況,你是否先刪除set pvtCache循環? –

+0

我在循環之前刪除了pvtCache,但仍然收到相同的錯誤。我已經設法縮小了這個問題的範圍,看起來只有當連接到克隆的數據透視表的切片器出現問題時 – Mike

0

得到周圍具有由數據源中的樞軸表的源轉換爲一個表,並改變爲表名生成數據集中的每個時間改變PivotCache。

Activesheet.ListObjects.Add(xlSrcRange, Range(Cells(1, "A").End(xlDown), Cells(1, "A").End(xlToRight)), , xlYes).Name = "DataTable" 
相關問題