我刚刚学习VBA,所以还没有完全熟悉它。
仅当数据透视表不存在时,我想创建一个具有动态范围的数据透视表。如果表已经存在,那么枢轴突出需要刷新。
到目前为止,我有这个:Sub CreatingPivot()
Dim PCache As PivotCache, LastRow As Long, pt As PivotTable
Dim ws As Worksheet
On Error Resume Next
Set ws = Sheets("Pivot")
If Err.Number <> 0 Then
Worksheets("Sheet1").Activate
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=1, SourceData:=Range("A1").CurrentRegion.Address)
Worksheets.Add
ActiveSheet.Name = "Pivot"
ActiveWindow.DisplayGridlines = False
Set pt = ActiveSheet.PivotTables.Add(PivotCache:=PCache, TableDestination:=Range("A1"), TableName:="PivotTable1")
Else
Sheets("Pivot").RefreshTable
End If
End Sub
答案 0 :(得分:1)
尝试类似:
Dim PivTbl as PivotTable
On Error Resume Next
Set PivTbl = Sheets("Pivot").PivotTables("PivotTable1")
On Error Goto 0
If PivTbl Is Nothing Then
'Create pivot table
End If
'Do your stuff
编辑OP评论/跟随Q
刷新数据透视表而不是工作表
Dim PivTbl As PivotTable
Set PivTbl = Sheets("Pivot").PivotTables("PivotTable1")
PivTbl.RefreshTable