Changing the data source for pivot using VB

Mannington

New Member
Joined
Feb 2, 2011
Messages
8
I have a workbook, where I have named the sheet using a cell reference, eg 032013. I have then created a pivot table on a seperate sheet. Each month a new sheet is created, with the new sheet name, eg. 042013, 052013. I want to change the data source to the new sheet name each month. I seem to be having problems with the sheet name reference, the code below works, but if I try to give it a sheet name based on cell reference it does not work. Any help would be appreciated.

sub update

Sheets("Summary").Select ' contains the pivot table

Dim ptMyPivotTable as PivotTable

Set ptMyPivotTable = ActiveSheet.PivotTables("PivotTable2")

ptMyPivotTable.SourceData= Sheets("032013").Range("a1").CurrentRegion.Address(true, True, xlR1C1, True)

ptMyPivotTable.PivotCache.Refresh

end sub
 

Excel Facts

How to total the visible cells?
From the first blank cell below a filtered data set, press Alt+=. Instead of SUM, you will get SUBTOTAL(9,)
Maybe something like this

Assumes
Sheetnames always have 6 digits
Reference cell = Summary!G1 (adjust to suit)

Code:
Sub update()
    Dim sheetName As String, ptMyPivotTable As PivotTable
    
    With Sheets("Summary")
        sheetName = .Range("G1").Value '<--Adjust
        sheetName = Format(sheetName, "000000")
            
        Set ptMyPivotTable = .PivotTables("PivotTable2")
        ptMyPivotTable.SourceData = _
            Sheets(sheetName).Range("A1").CurrentRegion.Address(True, True, xlR1C1, True)
        ptMyPivotTable.PivotCache.Refresh
    End With
 
End Sub

M.
 
Upvote 0

Forum statistics

Threads
1,214,431
Messages
6,119,457
Members
448,898
Latest member
drewmorgan128

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