简体   繁体   中英

Excel VBA re-apply pivot table data source

I have a macro that copies two sheets from my workbook to their own workbook. One sheet has some data defined with a named range, the second has multiple pivot tables, all with the data source as said named range candData .

Once the sheets have copied my slicers lose some of their Report Connections.

在此处输入图片说明

In order to reconnect them, I have to manually select each pivot table and set the data source again, even though the data source is already set. (I simply click Change Data Source and immediately click OK, without actually changing anything.)

Once I have done this for each pivot table all report connections are showing again.

在此处输入图片说明

I have the following macro to loop through each pivot table and re apply the data source, then reconnect each slicer connection, however even after the data source has been applied, I still have to manually select each pivot table in order to reconnect the slicers.

I am getting no errors, it steps through each pivot table as expected and resets the data source. Any clues why the report connections only work when I set the data source manually instead of through the following?

Sub setSlicerSource()

Dim MyPivot As PivotTable
Dim slCaches As SlicerCaches
Dim slCache As SlicerCache

Set slCaches = ActiveWorkbook.SlicerCaches

With ActiveWorkbook
    For Each MyPivot In .Sheets("Pivots").PivotTables
        MyPivot.ChangePivotCache .PivotCaches.Create(SourceType:=xlDatabase, SourceData:="candData")
    Next MyPivot

    For Each slCache In slCaches
        For Each MyPivot In .Sheets("Pivots").PivotTables
            slCache.PivotTables.AddPivotTable MyPivot
        Next MyPivot
    Next slCache
End With
End Sub

I'm not sure if this will actually solve your problem, but it's the first thing I'd try fixing regardless:

This line currently creates a new PivotCache for each PivotTable:

MyPivot.ChangePivotCache .PivotCaches.Create(SourceType:=xlDatabase, SourceData:="candData")

Instead, create a PivotCache for PivotTables(1) first before the loop:

.Sheets("Pivots").PivotTables(1).ChangePivotCache .PivotCaches.Create(SourceType:=xlDatabase, SourceData:="candData")

Then in the loop, set all PivotTables to use the cache of PivotTables(1)

MyPivot.ChangePivotCache .Sheets("Pivots").PivotTables(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM