Simple way to change a pivot cache

后端 未结 1 1002
感动是毒
感动是毒 2021-01-24 16:53

This doesn\'t work...

Sub changeData_Error()

Dim pc As PivotCache
Set pc = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Range(\"A1:B2\"))         


        
相关标签:
1条回答
  • 2021-01-24 17:36

    The following code switches between two different datasets, easily seen visibly by the presence/absence of Col3 in the Field List for the Pivot report:

    Option Explicit
    
    Public Sub SwitchToData1()
        On Error GoTo ErrHandler
        SwitchCacheData _
            ThisWorkbook.Sheets("Report").PivotTables("PivotTable1"), _
            Range("Data1!A1:B4")
    EndSub:
        Exit Sub
    
    ErrHandler:
        MsgBox "Error #" & Err.Number * vbCrLf & Err.Description, _
            vbOKOnly Or vbCritical, _
            "Error!"
        Resume EndSub
    End Sub
    
    
    Public Sub SwitchToData2()
        On Error GoTo ErrHandler
        SwitchCacheData _
            ThisWorkbook.Sheets("Report").PivotTables("PivotTable1"), _
            Range("Data2!A1:C4")
    EndSub:
        Exit Sub
    
    ErrHandler:
        MsgBox "Error #" & Err.Number * vbCrLf & Err.Description, _
            vbOKOnly Or vbCritical, _
            "Error!"
        Resume EndSub
    End Sub
    
    Private Sub SwitchCacheData(pvt As PivotTable, rng As Range)
        pvt.ChangePivotCache ThisWorkbook.PivotCaches.Create(xlDatabase, rng)
        pvt.RefreshTable
    End Sub
    
    0 讨论(0)
提交回复
热议问题