Excel VBA /button同时刷新两个或更多枢轴

在另一篇文章中,我提供了下面的VBA代码来附加到“刷新”button来刷新枢轴数据:

Option Explicit Sub Button5_Click() Dim PvtTbl As PivotTable Dim PvtCache As PivotCache Dim PvtDataRng As Range ' Set/Update Pivot Data Range Set PvtDataRng = Worksheets("PivotDataSheet").Range("A1:E100") ' <-- just an example ' Create/Update Pivot Cache Set PvtCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, PvtDataRng) ' Set the Pivot Table (already created, otherwise need to create it) Set PvtTbl = Worksheets("DD").PivotTables("test") ' refresh the Pivot Table with the latest Pivot Cache With PvtTbl .ChangePivotCache PvtCache .RefreshTable End With End Sub 

如何修改这个代码来同时刷新同一工作表中的第二个数据透视表? 让我们调用这个第二支点“test2”,它也在DD工作表中。

谢谢,Kevbo

如果在“DD”工作表中只有这2个PivotTable表,并且想要基于相同的PivotCache更新这两个数据PivotCache ,则请replace以下For循环:

 With PvtTbl .ChangePivotCache PvtCache .RefreshTable End With 

用下面的For循环:

 ' refresh all Pivot Tables in "DD" worksheet For Each PvtTbl In Worksheets("DD").PivotTables With PvtTbl .ChangePivotCache PvtCache .RefreshTable End With Next PvtTbl 

编辑1 :在For循环中Set PivotCache ,并在最后清除它。 使用下面的循环,并从它的上一个地方删除Set PvtCache行。

 ' refresh all Pivot Tables in "DD" worksheet For Each PvtTbl In Worksheets("DD").PivotTables ' Create/Update Pivot Cache Set PvtCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, PvtDataRng) With PvtTbl .ChangePivotCache PvtCache .RefreshTable End With Set PvtCache = Nothing ' <-- clear the Pivot Cache Next PvtTbl 

我自己没有testing过,但是你可以试着告诉我它是否工作。 它似乎可能适合你

 Function refreshPTcontent() Dim ws As Worksheet Dim pt As PivotTable Dim pf As PivotField Dim pi As PivotItem On Error Resume Next For Each ws In ActiveWorkbook.Worksheets For Each pt In ws.PivotTables pt.RefreshTable Next pt Next ws End Function