运行时错误1004 - 用于更新数据透视表的宏

时间:2017-08-01 09:37:22

标签: vba excel-vba pivot-table excel

我正在尝试使用宏更新数据透视表,因为每月将数据添加到表的底部(更新以包括数据到最后一行)。

Option Explicit

Sub Pivot()

Dim shConD As Worksheet
Dim shPvtTbl As Worksheet
Dim lr As Long
Dim rng As Range

Set shConD = ActiveWorkbook.Sheets("Consolidated_Data")
Set shPvtTbl = ActiveWorkbook.Sheets("PivotTables")

lr = shConD.Range("A" & Rows.Count).End(xlUp).Row
Set rng = shConD.Range("A1:F" & lr)

With shPvtTbl.PivotTables(3).PivotCache
     .SourceData = rng.Address(True, True, xlR1C1, True) 'Error appears here
     .Refresh
End With

End Sub

.SourceData行上,我收到运行时错误1004,应用程序定义或对象定义错误。遵循此thread和继续chat的逻辑。先谢谢你们。

2 个答案:

答案 0 :(得分:0)

尝试下面的代码(代码注释中的解释):

Option Explicit

Sub Pivot()

Dim shConD As Worksheet
Dim shPvtTbl As Worksheet
Dim lr As Long
Dim rng As Range

' Added PivotTable variables
Dim PvtTbl As PivotTable
Dim PvtCache As PivotCache

Set shConD = ActiveWorkbook.Sheets("Consolidated_Data")
Set shPvtTbl = ActiveWorkbook.Sheets("PivotTables")

lr = shConD.Range("A" & shConD.Rows.Count).End(xlUp).Row
Set rng = shConD.Range("A1:F" & lr)

' set/update the PivotCache (with latest rng modifications
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rng.Address(False, False, xlA1, xlExternal))
' for DEBUG Only
Debug.Print PvtCache.SourceData

' set the PivotTable object
Set PvtTbl = shPvtTbl.PivotTables(3)
' for DEBUG Only
Debug.Print PvtTbl.Name

' refresh the PivotTable with the updated PivotCache
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTable

End Sub

答案 1 :(得分:0)

如果您使用的是Excel 2007或更高版本,那么实现此目的的最简单方法是确保您的数据透视表源数据是Excel表(也称为ListObject),并使用更改数据透视表数据源中的表名称如下图所示。

感谢Tables的神奇之处,从那时起,无论何时向表中添加新数据,它都会自动扩展。每当您刷新数据透视表时,它将始终自动获取新数据。无需再次更改数据透视表数据源。

enter image description here