views:

521

answers:

2

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?

A: 

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.

Christian Payne
The whole point of using a Pivot Chart was so I could create a Pivot Table. The sequence of the chart creation follows: Pull data into Pivot table, add a named range to that pivot range, create chart off that pivot table but referencing it through the created named range
TheObserver
A: 

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

Sheets(wsName).Select
Range("A1").Select
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.

TheObserver
Not sure why the SetSourceData method is being run twice with slightly different syntax. Source is the first parameter and the only required one so both lines should have identical results
barrowc
Good call. That was a typo which was actually corrected in the original code later.
TheObserver