在VBA的帮助下,我可以创建数据透视表。但是当在工作表中添加新行并使用wksSource1.PivotTables(1).RefreshTable
刷新数据透视表时,它不会更新数据透视表。
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim lastrowv As Long
Dim lastcolv As Long
lastrowv = wksSource.Cells(Rows.Count, 3).End(xlUp).Row
lastcolv = wksSource.Cells(5, Columns.Count).End(xlToLeft).Column
Set PRange = wksSource.Cells(5, 1).Resize(lastrowv - 4, lastcolv)
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
PRange, Version:=xlPivotTableVersion14).CreatePivotTable _
TableDestination:=wksSource1.Cells(1, 1), TableName:="PivotTable14", _
DefaultVersion:=xlPivotTableVersion14
wksSource1.Select
Cells(1, 1).Select
With ActiveSheet.PivotTables("PivotTable14").PivotFields("Term - Phases")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable14").PivotFields("Status")
.Orientation = xlColumnField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable14").AddDataField ActiveSheet.PivotTables( _
"PivotTable14").PivotFields("Steps/ Activities"), "Count of Steps/ Activities" _
, xlCount
答案 0 :(得分:-1)
wksSource1.PivotTables(1).RefreshTable仅在数据透视缓存源数据是动态的情况下才有效,即源数据是excel表数据或动态命名范围。
但是在创建数据透视表时,源数据范围是固定的,取决于范围PRange。
因此,当您在源数据表上添加新数据时,数据透视缓存仍然会引用未以某种方式重置的PRange。
如果要刷新子例程中的数据透视表,则需要更新现有数据透视表缓存而不是刷新数据透视表,更新数据透视表缓存后,数据透视表也将更新。
尝试以下代码并根据需要进行调整。
Sub RefreshPivotTable()
Dim wksSource As Worksheet, wksSource1 As Worksheet
Dim PRange As Range
Dim lastrowv As Long, lastcolv As Long
Set wksSource = Sheets("Sheet4") 'Sheet which contains the source data for pivot table
Set wksSource1 = Sheets("Sheet3") 'Sheet which contains Pivot table
lastrowv = wksSource.Cells(Rows.Count, 3).End(xlUp).Row
lastcolv = wksSource.Cells(5, Columns.Count).End(xlToLeft).Column
Set PRange = wksSource.Range("C5:F12")
wksSource1.PivotTables(1).ChangePivotCache ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange)
End Sub