I’m trying to add many series to a chart using VBA, as in the code below.
For i = 0 To 9
Set serNew = chtMap.SeriesCollection.NewSeries
With serNew
.XValues = Range("Y4").Cells(1, 1 + 2 * i).Resize(32000, 1)
.Values = Range("Y4").Cells(1, 2 + 2 * i).Resize(32000, 1)
End With
Next i
The ranges for some of the series have no data in their cells yet; the user will write/load this data later. The idea is to have the chart ready for when they do.
Problem: when the loop hits such a yet empty range, I get an error 1004: Unable to set XValues property of the Series class. Why and is there a way around this?
The weird thing is that doing this manually in Chart menu –> |Source Data… works perfectly fine. Actually, if you record a macro while doing this manually, the result is as follows:
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(4).XValues = "=Sheet2!R4C31:R32003C31"
ActiveChart.SeriesCollection(4).Values = "=Sheet2!R4C32:R32003C32"
but then Excel gives an error when re-playing this macro!
Doing this manually is not a pleasant prospect. I guess I could stick sham data in the cells, create the series, and then delete the sham data. Do I really have to pull such a bait and switch on Excel?
I’ve decided to add a sheet button that calls a sub that can add the series after the data has been entered. It also checks whether the various ranges are empty before actually adding each series. This feels like the cleanest solution.