使用VBA更改数据透视表数据源

我试图自动尝试在Excel中更改数据透视表的“数据源”。 我尝试了大部分(如果不是全部)Google / Stack Overflow上可用的解决scheme。 但是我不断遇到以下错误。

Run-time error '5': Invalid procedure call or argument 

这是我运行失败的代码。

 Sub UpdateResourcePivots() Dim pivotDataSheet As Worksheet Dim dataSheet As Worksheet Dim pivotLocation As String Dim pivotDesignation As String Dim startPoint As Range Dim endPoint As Range Dim dataRange As Range Dim newRange As String Dim lastRow As Integer Dim newPivotCache As PivotCache Set pivotDataSheet = ThisWorkbook.Worksheets("PivotData") Set dataSheet = ThisWorkbook.Worksheets("Team Information") pivotLocation = "pvtResourceLocation" pivotDesignation = "pvtResourceDesignation" 'Dont worry about this one for now Set startPoint = dataSheet.Range("A5") lastRow = dataSheet.Range("A" & dataSheet.Rows.count).End(xlUp).row Set endPoint = dataSheet.Range("O" & lastRow) Set dataRange = dataSheet.Range(startPoint, endPoint) newRange = "'" & dataSheet.name & "'!" & dataRange.Address(RowAbsolute:=True, ColumnAbsolute:=True, ReferenceStyle:=xlR1C1, External:=True) ' newRange = "'" & dataSheet.name & "'!" & dataRange.Address(ReferenceStyle:=xlR1C1) ' Tried this as well Set newPivotCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=newRange, Version:=xlPivotTableVersion10) With pivotDataSheet .PivotTables(pivotLocation).ChangePivotCache newPivotCache 'Error thrown here. End With End Sub 

错误发生在以下行:

 .PivotTables(pivotLocation).ChangePivotCache newPivotCache 

其他一些信息

我正在使用MS Office 2010(许可)。 我有一个数据源(一个有20行和8列的小表格,这些行会增长,因此macros)。 在另一张纸上创build了两个数据透视表。 在第三张纸上,我使用切片器来过滤数据(仪表板)。

更改代码,以便在将其分配给数据透视表时创buildcaching:

 With pivotDataSheet .PivotTables(pivotLocation).ChangePivotCache ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=dataRange.Address(Referencestyle:=xlR1C1), Version:=xlPivotTableVersion10)