我有PivotTable
它的范围和数据总是在变化我有以下数据:
Range("A3").Select
Selection.CurrentRegion.Select
DataArea = "Sheet21!R1C1:R" & Selection.Rows.Count & "C" & Selection.COLUMNS.Count
ActiveSheet.PivotTables("PivotTable7").ChangePivotCache ActiveWorkbook. _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:=DataArea, _
Version:=xlPivotTableVersion15)
我收到错误
无法获取Worksheet类的PivotTables属性
答案 0 :(得分:0)
代码将使用PivotTable
中的SourceData
修改“Sheet1”中的“PivotTable7”(使用Worksheets("Sheet21").Range("A3").CurrentRegion
修改工作表的名称)。
Option Explicit
Sub ChangePivotTableCache()
Dim PvtTbl As PivotTable
Dim DataArea As String
' fully qualify your range by adding the worksheet object
With Worksheets("Sheet21").Range("A3").CurrentRegion
DataArea = "Sheet21!R1C1:R" & .Rows.Count & "C" & .Columns.Count
End With
On Error Resume Next
Set PvtTbl = Worksheets("Sheet1").PivotTables("PivotTable7") '<-- modify "Sheet1" to your sheet's name
On Error GoTo 0
If Not PvtTbl Is Nothing Then ' <-- If pivot table exist
PvtTbl.ChangePivotCache ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=DataArea)
Else ' <-- If pivot table doesn't exist
MsgBox "Pivot Table doesn't exist in worksheet!"
End If
End Sub
注意:获取String
的{{1}}你也可以使用:
SourceData