使用VBA更改数据透视表的数据源

Pop*_*diu 3 pivot-table microsoft-excel

我正在寻找一种代码,可以使用不同的数据源从一张工作表更改数据透视表的数据源。数据源表完全相同,只是数据不同。

我有一个从互联网上获取的代码,但它没有更改活动工作表的数据源,而是更改了所有工作表上的数据源。

遗憾的是,我对 VBA 编码了解不多,不知道如何更改代码以仅影响我的活动工作表,我希望有人可以帮助我。

Option Explicit

Sub ChangeDataSourceForAllPivotTables()

    Dim wb                  As Workbook
    Dim ws                  As Worksheet
    Dim pt                  As PivotTable
    Dim rSourceData         As Range

    If ActiveWorkbook Is Nothing Then Exit Sub

    On Error GoTo ErrHandler

    Set wb = ActiveWorkbook

    Set rSourceData = wb.Worksheets("Sheet1").Range("A1").CurrentRegion 'change the name of the worksheet accordingly

    For Each ws In wb.Worksheets
        For Each pt In ws.PivotTables
            pt.ChangePivotCache wb.PivotCaches.Create(xlDatabase, rSourceData.Address(, , , True))
            pt.RefreshTable
        Next pt
    Next ws

ExitTheSub:
    Set wb = Nothing
    Set ws = Nothing
    Set pt = Nothing
    Set rSourceData = Nothing

    Exit Sub

ErrHandler:
    MsgBox "Error " & Err.Number & ":  " & Err.Description, vbCritical, "Error"
    Resume ExitTheSub

End Sub
Run Code Online (Sandbox Code Playgroud)

预先感谢您的帮助!

Raj*_*nha 5

此代码将帮助您更改特定工作表中所有数据透视表的源数据。

Sub ChangePivotSourceData()

Dim pt As PivotTable

For Each pt In ActiveWorkbook.Worksheets("Sheet1").PivotTables
         pt.ChangePivotCache ActiveWorkbook.PivotCaches.Create _
            (SourceType:=xlDatabase, SourceData:="MyData")
Next pt

End Sub
Run Code Online (Sandbox Code Playgroud)

怎么运行的:

  • Copy&Paste此代码为Standard Module.
  • Sheet并且Source Data名称是可编辑的。
  • 在此代码中,MyData是一个命名范围, 每次您想要更改数据透视表的源数据时,您都需要在运行此代码之前创建它。