在用vba操作数据透视表时,经常需要更新数据透视表。
使用vba更新数据透视表,可以使用数据透视表对象PivotTable更新也可以使用数据透视表的缓存对象PivotCache更新。
vba中内置了很多透视表的更新方法,接下来一一介绍:
方法1:使用PivotTable对象的RefreshTable方法更新数据透视表,如果更新成功,将会返回True。
特别提醒:不能使用PivotTable对象的Update方法更新数据透视表,这个方法无法更新数据透视表。
Sub QQ1722187970()
Dim oPC As PivotCache
Dim oPT As PivotTable
Dim oWK As Worksheet
Set oWK = Excel.ActiveSheet
Set oPT = oWK.PivotTables(1)
With oPT
'刷新透视表
MsgBox .RefreshTable
End With
End Sub
方法2:使用PivotCache对象的Refresh方法更新数据透视表的缓存。
Sub QQ1722187970()
Dim oPC As PivotCache
Dim oPT As PivotTable
Dim oWK As Worksheet
Set oWK = Excel.ActiveSheet
Set oPT = oWK.PivotTables(1)
With oPT
'获取数据透视表的缓存
Set oPC = .PivotCache
With oPC
'更新数据透视表
.Refresh
End With
End With
End Sub
以上是两种最常见的更新数据透视表的方法。


发表评论