尊敬的专家,我正在尝试执行以下VBA代码来定义我的数据并刷新数据透视表,但我得到已定义或对象定义错误-1004 。请在下面指导我在哪里犯错误。
Sub Pivot()
Dim shPivot As Worksheet
Dim shData As Worksheet
Dim lr As Long
Dim lc As Long
Dim rng As Range
Set shPivot = ActiveWorkbook.Sheets("Data")
Set shData = ActiveWorkbook.Sheets("Pivot")
lr = shPivot.Range("A" & Rows.Count).End(xlUp).Row
Set rng = shPivot.Range(Cells(1, 1), Cells(lr, 32))
With shData.PivotTables("PivotTable1").PivotCache
.SourceData = rng.Address(True, True, xlR1C1, True)
.Refresh
End With
End Sub
答案 0 :(得分:1)
尝试以下代码:
Option Explicit
Sub Pivot()
Dim shPivot As Worksheet
Dim shData As Worksheet
Dim PT As PivotTable
Dim PTCache As PivotCache
Dim lr As Long
Dim lc As Long
Dim Rng As Range
Set shPivot = ActiveWorkbook.Sheets("Data")
Set shData = ActiveWorkbook.Sheets("Pivot")
With shPivot
lr = .Range("A" & .Rows.Count).End(xlUp).Row
Set Rng = .Range(.Cells(1, 1), .Cells(lr, 32))
End With
' set the Pivot Cache with the updated Data Source
' Set PTCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Rng)
' === Option 2 : set the Pivot Cache with the updated Data Source ===
Set PTCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=shPivot.Name & "!" & Rng.Address(True, True, xlR1C1, False))
' Set the Pivot Table to existing "PivotTable1" in "Data" sheet
Set PT = shData.PivotTables("PivotTable1")
With PT
.ChangePivotCache PTCache
.RefreshTable
End With
End Sub