我正在尝试动态刷新Excel中的某些数据透视表。数据透视表(以及连接的切片器 - 每个切片器连接到多个枢轴)已经存在,而基础源数据表则不存在。过程如下:
澄清结构: 一个数据源表。多个数据透视表指向源。多个切片机,每个切片机连接到所有枢轴表(例如,周末切片机在所有枢轴上切割周末)
我遇到了问题但步骤4.以下代码有效:
'dataTable is a ListObject that was created on a sheet earlier in the function. Can confirm 100% that it exists and is populated.
Dim pt As PivotTable
For Each pt in PivotSheet.PivotTables
pt.ChangePivotCache ThisWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=dataTable)
Next pt
但是,它意味着每个数据透视表有一个数据透视缓存,这意味着我在尝试设置操纵多个数据的切片器时会遇到问题 - 它假定每个数据透视表都有不同的数据源,因此只会让我链接切片机到一个支点。
我决定要创建单个数据透视缓存,然后将每个数据透视表链接到它。但是这段代码不起作用,第一次到达时就把error 5
扔给了我:
'dataTable is a ListObject that was created on a sheet earlier in the function. Can confirm 100% that it exists and is populated.
Dim pc As PivotCache
Set pc = ThisWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=dataTable)
Dim pt As PivotTable
For Each pt in PivotSheet.PivotTables
pt.ChangePivotCache pc 'Invalid Procedure Call Or Argument
Next pt
我在这里做错了什么?
答案 0 :(得分:1)
结合两种方法:
Dim bCreated As Boolean
Dim lngMasterIndex As Long
Dim pt As PivotTable
For Each pt In PivotSheet.PivotTables
If Not bCreated Then
pt.ChangePivotCache ThisWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=DataTable)
bCreated = True
lngMasterIndex = pt.CacheIndex
Else
pt.CacheIndex = lngMasterIndex
End If
Next pt
答案 1 :(得分:0)
如果你不喜欢浮潜代码,为了让它运行起来,这是一个简短而又脏的方法:
For Each pt in PivotSheet.PivotTables
On Error Resume Next
pt.ChangePivotCache pc 'works for the first entry
pt.CacheIndex = pc.Index 'works for all the others
On Error GoTo 0
Next PT