使用VBA创建数据透视表时出错

时间:2017-04-04 08:26:03

标签: excel-vba pivot-table vba excel

我正在尝试使用VBA代码创建数据透视表。但它总是显示运行时错误'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")

这段代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

下面的代码Set pvt以防它已经创建(来自之前的代码运行),并且仅使用更新的PivotCache更新数据透视表。

如果“Sheet2”中尚不存在“PivotTable1”,则在“Sheet2”中创建它。

<强>代码

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
相关问题