小编Pop*_*diu的帖子

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

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

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

遗憾的是,我对 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 = …
Run Code Online (Sandbox Code Playgroud)

pivot-table microsoft-excel

3
推荐指数
1
解决办法
4万
查看次数

标签 统计

microsoft-excel ×1

pivot-table ×1