Excel数据透视表更新 – 不创build数据透视表(VBA)

由于EPPlus不支持数据透视表源代码范围的操作(更具体地说,可以更新caching定义,但是一旦文件被保存,这个更新不会被保留),我必须在模板本身中使用VBA来更新源代码范围和刷新数据透视表。

有两个数据源分别存储在该文件中的两个数据透视表和两个关联的PivotCache对象。 我的目标是将所有数据透视表更新为2个来源中的新单元格区域。 由于我不想复制一堆PivotCaches来执行此操作,因此我只创build第一个,然后尝试更新将相关数据集共享到相同caching的后续数据透视表。

这里是从一个caching(“下载”)更新枢轴的摘录。 该函数的其余部分对第二个caching做了完全相同的事情(它嵌套在相同的循环中,但是为了简洁起见而省略)。

 Set downloads = ThisWorkbook.Worksheets("DLRaw") For Each ws In ActiveWorkbook.Worksheets For Each pt In ws.PivotTables If Not downloadsCreated Then Set startCell = downloads.Range("A8") Set endCell = downloads.Range("Y" & startCell.SpecialCells(xlLastCell).Row) Set dataRange = downloads.Range(startCell, endCell) newRange = downloads.Name & "!" & dataRange.Address(ReferenceStyle:=xlR1C1) pt.ChangePivotCache _ ThisWorkbook.PivotCaches.Create(xlDatabase, newRange) Set downloadsCache = pt.PivotCache downloadsCreated = True Else If pt.CacheIndex <> downloadsCache.Index Then pt.CacheIndex = downloadsCache.Index End If pt.RefreshTable For Each rf In pt.RowFields If rf.Position <> pt.RowFields.count Then rf.ShowDetail = False End If Next rf For Each cf In pt.ColumnFields If cf.Position <> pt.ColumnFields.count Then cf.ShowDetail = False End If Next cf Next pt Next ws 

我始终得到关于空实体的运行时错误“1004”,由Else块中的行抛出。 通过代码,我注意到新创build的透视caching的CacheIndex0 ,所以要么不分配downloadsCachecaching对象,要么没有创build新的caching。 我看到范围variables中的正确值。 这个行为同时存在于上面的下载片段和第二个caching的数据透视表中。

任何关于下一步看什么的想法,或者如果有必要的话,解决这个问题的不同方法?

请尝试下面的代码,以便使用一个PivotCache更新工作表中的所有PivotTable PivotCache

 Option Explicit Sub UpdatePivotTables() Dim ws As Worksheet Dim downloads As Worksheet Dim PT As PivotTable Dim PTCache As PivotCache Dim startCell As Range, endCell As Range Dim dataRange As Range Dim newRange As String Set downloads = ThisWorkbook.Worksheets("DLRaw") For Each ws In ActiveWorkbook.Worksheets ' the Range setting needs to be done once >> take outside the loop Set startCell = downloads.Range("A8") Set endCell = downloads.Range("Y" & startCell.SpecialCells(xlLastCell).Row) Set dataRange = downloads.Range(startCell, endCell) newRange = dataRange.Address(False, False, xlR1C1, xlExternal) '<-- get the range address including the sheet's name (and workbook if needed) For Each PT In ws.PivotTables ' set the pivot cache Set PTCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=newRange) ' update the Pivot Table with the updated Pivot Cache's Source Data PT.ChangePivotCache PTCache PT.RefreshTable Set PTCache = Nothing ' reset for next cycle Next PT Next ws End Sub