I am working on a larger project that involves making a worksheet with up to 100 different charts (in this case XY scatter charts). I have seen on other threads that it is not efficient to activate charts every time you want to make a change. In this sub I am just running through a loop to create 120 blank charts, and will later add data and format. Here is my code:
Global Const numCharts = 120
Private Charts()
ReDim Charts(numCharts)
Sub createCharts()
For graphIndex = 1 To numCharts
'adds the new chart in the specified loaction
Set Charts(graphIndex) = ActiveSheet.ChartObjects.Add(Left:=chartTopLeftX, Top:=chartTopLeftY, Width:=chartWidth, Height:=chartHeight)
Charts(graphIndex).Name = activeSheetName & graphIndex
Charts(graphIndex).ChartType = xlXYScatter
'changes the top left coordinate varibales for the following chart
If graphIndex Mod 2 = 1 Then
chartTopLeftX = chartTopLeftX + chartWidth + chartGap
'chartTopLeftY = chartTopLeftY
Else
chartTopLeftX = chartTopLeftX - chartWidth - chartGap
chartTopLeftY = chartTopLeftY + chartHeight + chartGap
End If
Next graphIndex
End Sub
The Charts(graphIndex).Name line works fine, but I get an error on the Charts(graphIndex).ChartType line. If I activate the chart first I can just use ActiveChart.ChartType, but I am trying to avoid that. Hopefully this makes sense. I have run into this issue in the past when working with chart objects, but can't seem to find a good explanation on why?
Edit: I'm sorry I should have specified this, but there are many variables decalred in the module, outside of this sub. The code runs perfectly fine without the Charts(graphIndex).ChartType line. I may not be handling this correctly, but I tried to create an array to hold the chart objects.
Charts?Charts(graphIndex)will error out as #9. the code you have posted will never get past that line.Charts()array was declared and defined separately in the module. The issue I was having was just with changing the chart type without having to activate the chart.