VBA运行时1004“引用无效” – 透视刷新macros

我试图运行这个非常简单的代码,我已经embedded到一个button刷新枢纽:

Sub Button5_Click() ThisWorkbook.Worksheets("DD").PivotTables("test").PivotCache.REFRESH End Sub 

在下面的照片中,您可以看到我正在处理的工作表以及透视的名称。

它看起来像我的代码指向正确的事情,所以我不明白为什么我得到这个错误。 我也尝试过不使用ThisWorkbook。

工作簿照片

在这里输入图像说明

为了更新“DD”工作表中的数据PivotTables("test")中的数据,您需要首先更新PivotTable的数据PivotTablePivotTable检索数据的范围中的更新PivotTable PivotCache 。 然后Refresh表格。

我已经使用下面这行来定义PivotCacheRange (只是为了运行这段代码):

 Set PvtDataRng = Worksheets("PivotDataSheet").Range("A1:E100") 

修改工作表的名称和needee范围以适合您的数据。

 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