我正在使用V.B.A代码动态更改数据透视表的数据源范围。包含数据透视表的工作表位于不同的工作表( Sheet7 )(在同一个Excel文件中),数据源位于 Sheet2 中,并且宏在 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( _
它提供运行时错误'':对象不支持此属性或方法
答案 0 :(得分:1)
PivotCaches
与工作簿绑定,而非工作表。
https://msdn.microsoft.com/en-us/vba/excel-vba/articles/pivotcaches-object-excel