运行时错误“5”:运行macros时,过程调用或参数无效

我正在使用VBA代码dynamic更改数据透视表的数据源范围 。 包含数据透视表的工作表位于不同的工作表( Sheet7 )中(在同一个Excel文件中),数据源位于Sheet2中 ,而macros在Sheet9中运行,即与数据源和数据透视表不同的工作表。 运行代码时抛出错误: 运行时错误“5”:无效的过程调用或参数 (注意:所有工作表都是相同的Excel文件)

代码如下:

Sub UPDATE_BUTTON() 'PURPOSE: Automatically readjust a Pivot Table's data source range 'SOURCE: www.TheSpreadsheetGuru.com/The-Code-Vault Dim Data_sht As Worksheet Dim Pivot_sht As Worksheet Dim StartPoint As Range Dim DataRange As Range Dim PivotName As String Dim NewRange As String 'Set Variables Equal to Data Sheet and Pivot Sheet Set Data_sht = ThisWorkbook.Worksheets("Sheet2") Set Pivot_sht = ThisWorkbook.Worksheets("Sheet7") 'Enter in Pivot Table Name PivotName = "A" 'Dynamically Retrieve Range Address of Data Set StartPoint = Data_sht.Range("A1") Set DataRange = Data_sht.Range(StartPoint, StartPoint.SpecialCells(xlLastCell)) NewRange = Data_sht.Name & "!" & _ DataRange.Address(ReferenceStyle:=xlR1C1) 'Make sure every column in data set has a heading and is not blank (error prevention) If WorksheetFunction.CountBlank(DataRange.Rows(1)) > 0 Then MsgBox "One of your data columns has a blank heading." & vbNewLine _ & "Please fix and re-run!.", vbCritical, "Column Heading Missing!" Exit Sub End If 'DataArea = "Sheet7!R1C1:R" & Selection.Rows.Count & "C" & Selection.Columns.Count 'Change Pivot Table Data Source Range Address Pivot_sht.PivotTables(PivotName).ChangePivotCache _ ThisWorkbook.PivotCaches.Create( _ SourceType:=xlDatabase, _ SourceData:=NewRange) 'Ensure Pivot Table is Refreshed Pivot_sht.PivotTables(PivotName).RefreshTable 'Complete Message MsgBox PivotName & "'s data source range has been successfully updated!" End Sub 

同样的是抛出一个错误的行:

 Pivot_sht.PivotTables(PivotName).ChangePivotCache _ ThisWorkbook.PivotCaches.Create( _ SourceType:=xlDatabase, _ SourceData:=NewRange) 

如果我改变一样:

 ThisWorkbook.Worksheets("Sheet7").PivotCaches.Create( _ 

它给运行时错误“438”:对象不支持此属性或方法

PivotCaches绑定到工作簿,而不是工作表。 https://msdn.microsoft.com/en-us/vba/excel-vba/articles/pivotcaches-object-excel