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

Excel 使用VBA创建数据透视表时出错,excel,pivot-table,vba,Excel,Pivot Table,Vba,我正在尝试使用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(Ref

我正在尝试使用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")

此代码有什么问题?

如果已经创建了数据透视表(从以前的代码运行),下面的代码将
设置pvt
,并且只使用更新的
数据透视缓存更新数据透视表

如果“数据透视表1”在“Sheet2”中尚不存在,则在“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

请参见下面的答案和代码,您的数据透视数据是否从第二行(
范围(“B2:M4”)
)开始?如果您的标题在第一行,那么您也需要它们