无法使用VBA刷新附加到表的数据透视表

时间:2016-09-28 17:14:52

标签: excel vba excel-vba

我将一系列单元转换为一个名为Table1的表。然后我插入了一个数据透视表,然后插入了这个:

Private Sub Worksheet_Change(ByVal Target As Range)
  Dim pt As PivotTable
  Set pt = ActiveSheet.PivotTables("PivotTable1")
  pt.PivotCache.Refresh
End Sub

我收到错误1004. DataSource是'Table1'

1 个答案:

答案 0 :(得分:0)

我将代码从Worksheet_Change事件移动到您可以通过按钮调用的Sub,否则每当有人修改或触摸此工作表中的任何位置时,它都会触发。

我将设置为“ Table1 ”的“ PivotSrc_Range ”定义为“{strong> Table1 ”,并且每次都设置为PivotCache有人修改或添加数据到“表1 ”,PivotCache更改,PivotTable将在您调用下面的Sub后修改:

Sub UpdatePivot()

Dim sht1                            As Worksheet
Dim pt                              As PivotTable
Dim PvtCache                        As PivotCache
Dim PivotSrc_Range                  As Range

' modify to your sheet name (I prefer not to use ActiveSheet)
Set sht1 = ThisWorkbook.Sheets("Sheet1")

' modify to your Table's name
Set PivotSrc_Range = sht1.Range("Table1")

' set the Pivot Cache
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PivotSrc_Range, Version:=xlPivotTableVersion14)

' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set pt = sht1.PivotTables("PivotTable1")

On Error GoTo 0
If pt Is Nothing Then

    ' create a new Pivot Table in "Sheet1" sheet, start from Cell I1
    Set pt = sht1.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=sht1.Range("I1"), TableName:="PivotTable1")
Else
    ' just refresh the Pivot cache with the updated Range (data in Table1)
    pt.ChangePivotCache PvtCache
    pt.RefreshTable
End If

End Sub