【问题标题】:How can I create VBA which creates a pivot table only if it doesn't already exist如何创建仅在数据透视表不存在时才创建数据透视表的 VBA
【发布时间】:2014-11-21 14:59:34
【问题描述】:

我刚学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

【问题讨论】:

    标签: vba excel pivot pivot-table


    【解决方案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
    

    【讨论】:

    • 我已经尝试过了,但是当枢轴已经存在时,我仍然无法刷新枢轴。还有其他建议吗?
    • @Julie Routley - 见编辑回答。
    猜你喜欢
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多