我一直在尝试使用VBA创建PivotTabl
e,但它一直在PivotCache
部分给出Pan错误消息。
我在工作簿上有三个工作表,我打算使用工作表1中的表在工作表3上创建数据透视表和图表。但是我一直收到错误消息。
这是我的vba代码:
Dim ws As Worksheet
Dim pc As PivotCaches
Dim pt As PivotTable
Dim Rng As Range
Dim wb As Workbook
Set ws = Worksheets("Sheet3")
Set Rng = Worksheets("Sheet3").Range("A58")
Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Table1", Version:=xlPivotTableVersion14)
Set pt = pc.CreatePivotTable(TableDestination _
:=Range("A58"), TableName:="PivotTable5", DefaultVersion:= _
xlPivotTableVersion14)
ActiveWorkbook.ShowPivotTableFieldList = True
End Sub
数据透视表数据屏幕截图
答案 0 :(得分:0)
尝试下面的代码,代码注释中的解释:
Option Explicit
Sub PivotTablefromTable()
Dim wb As Workbook
Dim ws As Worksheet
Dim PTbl As PivotTable
Dim PCache As PivotCache
Dim WorkTbl As ListObject
Dim PTblRng As Range
Dim Rng As Range
Set ws = Worksheets("Sheet3")
Set Rng = ws.Range("A58")
Set WorkTbl = Worksheets("work").ListObjects("Table1") ' <-- set a variable to the "Table1" in sheet "work"
Set PTblRng = WorkTbl.Range '<-- get the range from "Table1"
' set the Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PTblRng)
' Set the Pivot Table (already created in previous macro run)
On Error Resume Next
Set PTbl = ws.PivotTables("PivotTable5")
On Error GoTo 0
If PTbl Is Nothing Then ' <-- pivot table still doesn't exist >> need to create it
' create a new Pivot Table in ws sheet, start from Cell A58
Set PTbl = ws.PivotTables.Add(PivotCache:=PCache, TableDestination:=Rng, TableName:="PivotTable5")
' rest of your code here
Else ' just refresh the Pivot table, with updated Pivot Cache
PTbl.ChangePivotCache PCache
PTbl.RefreshTable
End If
ActiveWorkbook.ShowPivotTableFieldList = True
End Sub