我有大约十个数据透视表,每个都在另一个工作表上。
我需要将每个数据源的数据源更改为相同的值。 Pivotcaches.count
给我1本工作簿,所以我假设每个表都指向此缓存。
您对如何更改此缓存而不创建十个新缓存有一些建议吗?
这是我得到的:
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
这是它的实际外观。它说方法不匹配或类似。
答案 0 :(得分:2)
由于您只有一个Pivot Cache,因此需要创建一个新的Pivot Cache,然后将其应用到数据透视表。
此处,Pivot缓存是从名为Sheet_Name
的工作表中名为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
的范围创建的,我将其留给您重命名以满足您的需要! ;)
{{1}}
答案 1 :(得分:0)
我同意R3UK的回答,但我使用创建方法对数据透视表和数据透视表经历了太多的跨版本问题(Excel 2013到Excel 2010)。最后一个参数 Version 更改了其名称或Excel 2010(Application.Version 15.0)数据透视表标准( xlPivotTableVersion15 )在使用时无法被Excel 2010识别(应用程序。我想,版本14.0)(标准 xlPivotTableVersion14 )。
我发现添加方法风险较小。它可以用于以类似的方式轻松创建数据透视表。
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