I have multiple pivot charts each with their own pivot table on separate worksheets in Excel 2002.

When I try to generate these charts with VBA with the following code:

Set cht = Charts.Add(After:=Worksheets("Setup"))
With cht
    ' we use named ranges here
    .SetSourceData Source:=range(tblName)
    .Name = chtName


where tblName is a named range just created a few lines before, the code runs fine if there is only one table and chart generate but gives me a run time error 1004: "The source data of a PivotChart report cannot be changed..." if I try to generate pivot table and chart set one after another.

Going to Insert -> Name -> Define, the list of named ranges created seems to be correct.

What is the correct way of setting the source data for a pivot chart with a dynamic range?

Was it helpful?

Solution 2

This piece of code assumes that you have only one pivot table per sheet and the pivot table starts on Cell A1:

Set cht = Charts.Add(after:=Worksheets(Worksheets.Count))
With cht
    .SetSourceData Sheets(wsName).Range("A1")
    .Name = chtName


Also changing "Worksheets.Count" to a specific worksheet name seems to trigger that error as well.


I think you might be trying to do too many things at once.

If the Data Source is going to change, I wouldn't use a Pivot Chart.

Use a pivot table, create the chart at runtime (like your example). Build your chart of the results of the pivot table.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top