I'm trying to create a pivot table using VBA code. But it always show up the Run-time error '5'
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
SrcData = "Sheet1!" & Range("B2:M4").Address(ReferenceStyle:=xlA1)
StartPvt = "Sheet2!" & Range("A3").Address(ReferenceStyle:=xlA1)
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
Set pvt = pvtCache.CreatePivotTable(StartPvt, "PivotTable1")
What's wrong with this code?
The code below will Set pvt
in case it's already created (from previous code runs), and just updates the PivotTable with the updated PivotCache
.
If "PivotTable1" does not exist yet in "Sheet2", then creat it in "Sheet2".
Code
Option Explicit
Sub Pivot()
Dim PvtSht As Worksheet
Dim DataSht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
Set DataSht = Worksheets("Sheet1")
Set PvtSht = Worksheets("Sheet2")
SrcData = "Sheet1!" & DataSht.Range("B2:M4").Address(ReferenceStyle:=xlA1)
' Set the Pivot Cache
Set pvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData)
' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set pvt = PvtSht.PivotTables("PivotTable1") ' check if "PivotTable1" Pivot Table already created (in past runs of this Macro)
On Error GoTo 0
If pvt Is Nothing Then
' create a new "PivotTable1" in "Sheet2" sheet
Set pvt = PvtSht.PivotTables.Add(PivotCache:=pvtCache, TableDestination:=PvtSht.Range("A3"), TableName:="PivotTable1")
Else
' just refresh the Pivot cache with the updated Range
pvt.ChangePivotCache pvtCache
pvt.RefreshTable
End If
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.