VBA数据透视表范围变化

问题描述 投票:1回答:1

我有一个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属性

excel-vba vba excel
1个回答
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

注意:要获得StringSourceData,您还可以使用:

DataArea = "Sheet21!" & Worksheets("Sheet21").Range("A3").CurrentRegion.Address(True, True, xlR1C1)
© www.soinside.com 2019 - 2024. All rights reserved.