Change pivot table source via VBA?

TheWennerWoman

Active Member
Joined
Aug 1, 2019
Messages
303
Office Version
  1. 365
Platform
  1. Windows
I have a master file containing details of payroll for about 100 cost centres. I have managed to put together some code that splits it out into individual files. So, sample data
Cost centre (for Posting)Element TypePayroll Reference NoElementRoleSum of Value
C0010Admin
5778​
Basic SalaryDriver
100​
C0010Admin
5778​
Employers NIDriver
100​
C0020Admin
3221​
Basic SalaryRevenue Manager
100​
C0020Admin
3221​
Employers NIRevenue Manager
100​

My code will generate two files for this sample, one named C0010, the other named C0020. I'm doing this by copying the master sheet and a pivot table into a new file and then removing anything I don't need.

My problem is the pivot table. It is remembering the link to the master file. I tried this
VBA Code:
Sub Change_Pivot_Source_Data()

Dim pt As PivotTable

For Each pt In ActiveWorkbook.Worksheets("Pivot Report").PivotTables
         pt.ChangePivotCache ActiveWorkbook.PivotCaches.Create _
            (SourceType:=xlDatabase, SourceData:=Sheet1.Range("B2:G50000"))
 
Next pt

End Sub

But this isn't working, the pivot table in the new files are still pointing to the master file. Is there a quick fix or would I be better off creating a pivot table in each file from scratch? If the latter, how easy is that in VBA?

Thank you for reading.
 

Excel Facts

Why does 9 mean SUM in SUBTOTAL?
It is because Sum is the 9th alphabetically in Average, Count, CountA, Max, Min, Product, StDev.S, StDev.P, Sum, VAR.S, VAR.P.

Forum statistics

Threads
1,223,889
Messages
6,175,223
Members
452,620
Latest member
dsubash

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top