How to configure Pivot Table source data externally through VBA
A Pivot Table is linked to a particular source data. If for some reasons, you need that to be configured by users the following code will give some hint:
Sub Change_Pivot_TableDataSource()
Dim oPT As PivotTable
Dim oPC As PivotCache
Dim ORange As Range
Set oPT = ActiveSheet.PivotTables(1)
Set oPC = oPT.PivotCache
Set ORange = Application.InputBox(Prompt:="Select the New DataRange", Type:=8)
oPC.SourceData = "Sheet1!" & Application.ConvertFormula(ORange.Address, xlA1, xlR1C1)
oPT.RefreshTable
If Not oPT Is Nothing Then Set oPT = Nothing
If Not oPC Is Nothing Then Set oPC = Nothing
End Sub
The code gets the new data range through Input Box and modifies the SourceData of the Pivot Table. Change the Sheet name accordingly before you use the code.
oPC.SourceData = "Sheet1!" & Application.ConvertFormula(ORange.Address, xlA1, xlR1C1)
ReplyDeleteIt is not working
Not Working... The line mentioned in the comment before mine is wrong
ReplyDeleteCan you post the code and the error you get while you run . It hsould be helpful
ReplyDeleteI am also getting an error msg on the same line:
ReplyDeleteoPC.SourceData = "Category_Variance" & Application.ConvertFormula(ORange.Address, xlA1, xlR1C1)
Runtime error '1004'
Reference is not valid