更改现有透视caching的数据源

我有大约十个数据透视表,每个都在另一个工作表上。

我需要将它们中的每一个的数据源更改为相同的值。 Pivotcaches.count给我1这个工作Pivotcaches.count ,所以我假设每个表指向这个caching。

你有一些build议,如何改变这个caching,而不是创build十个新的?

这是我得到的:

 Sub Test(Ziel As String, Zieltab As String) Dim RNG As Range Dim letzteZeile As Double Dim letzteSpalte As Double Dim Spalte As String Dim Index As Integer Dim Wb As Workbook Dim Ws As Worksheet Dim pC As PivotCache Dim pT As PivotTable letzteZeile = Workbooks(Ziel).Worksheets(Zieltab).UsedRange.SpecialCells(xlCellTypeLastCell).Row letzteSpalte = Workbooks(Ziel).Worksheets(Zieltab).Range("A1").SpecialCells(xlCellTypeLastCell).Column Spalte = Split(Workbooks(Ziel).Worksheets(Zieltab).Cells(1, letzteSpalte).Address, "$")(1) Set RNG = Worksheets(Zieltab).Range("A1:" & Spalte & letzteZeile) Set Wb = ActiveWorkbook Set pC = Wb.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="'" & Wb.Sheets(Zieltab).Name & "'!" & RNG.Address, Version:=xlPivotTableVersion12) For Each Ws In Wb.Sheets For Each pT In Ws.PivotTables Set pT.PivotCache = pC Next pT Next Ws End Sub 

这是它的实际外观。 它说方法不会匹配或者像那样。

由于您只有一个透视caching,所以您需要创build一个新窗口,然后将其应用于您的透视表。

这里的Pivot Cache是​​从名为Named_Range的Sheet中名为Sheet_Name的范围创build的,我把它留给你来重新命名这些以适应你的需要! ;)

 Sub Test_Gring() Dim wB As Workbook, _ wS As Worksheet, _ pC As PivotCache, _ pT As PivotTable, _ bCreated As Boolean For Each wS In wB.Sheets For Each pT In wS.PivotTables If Not bCreated Then pT.ChangePivotCache wB.PivotCaches.Create(SourceType:=xlDatabase, _ SourceData:="'Sheet Name'!" & Range("Named_Range").Address, _ Version:=xlPivotTableVersion14) 'xlPivotTableVersion12 Set pC = pT.PivotCache bCreated = True Else If pT.CacheIndex <> pC.Index Then pT.CacheIndex = pC.Index End If Next pT Next wS 'Save to delete unused Pivot Caches wB.Save End Sub 

我同意R3UK的答案,但是我已经经历了太多的跨版本问题(Excel 2013到Excel 2010)使用数据透视表和数据透视表的Create方法。 我想,Excel 2010(Application.Version 14.0)(标准xlPivotTableVersion14 )无法识别Excel Server 2010(Application.Version 15.0)数据透视表标准( xlPivotTableVersion15 )使用时最后一个参数Version更改名称或Excel 2013(Application.Version 15.0)数据透视表标准( xlPivotTableVersion15 )。

我发现Add方法风险较小。 它可以用于以类似的方式轻松创build数据透视表。

 Sub ChangeCacheWithAdd() Dim wB As Workbook, _ wS As Worksheet, _ pC As PivotCache, _ pT As PivotTable, _ bCreated As Boolean For Each wS In wB.Sheets For Each pT In wS.PivotTables If Not bCreated Then Set pC = wB.PivotCaches.Add(SourceType:=xlDatabase, _ SourceData:="'Sheet Name'!" & Range("Named_Range").Address pT.ChangePivotCache pC bCreated = True Else If pT.CacheIndex <> pC.Index Then pT.CacheIndex = pC.Index End If Next pT Next wS 'Save to delete unused Pivot Caches wB.Save End Sub