Reputation: 69
I am working on plotting a chart on several sheets. Initially, I use macro-recording but it only assigns a specific sheet without able to obtain the data on every sheet.
Here is the code
ActiveSheet.Shapes.AddChart2(240, xlXYScatterSmooth).Select
ActiveChart.SetSourceData Source:=Range( _
"Sheet12!$A$20:$A$54,Sheet12!$C$20:$D$54")
I tried to assign using the active worksheet as follow:
ActiveChart.SetSourceData Source:=Range( _
"ActiveWorksheet!$A$20:$A$54,ActiveWorksheet!$C$20:$D$54")
But unfortunately, it didn't work. Could you help me to fix the code to work with the active worksheet so I can work on several sheets? Thank you in advance
Upvotes: 1
Views: 601
Reputation: 6053
A slightly more robust solution would be:
ActiveChart.SetSourceData Source:=ActiveSheet.Range( _
ActiveSheet.Range("$A$20:$A$54"),ActiveSheet.Range("$C$20:$D$54"))
Upvotes: 0
Reputation: 1497
I have two ideas. Both untested.
A. You could try removing references to the specific sheet (which you have replaced with activesheet) in the range definitions, like below.
ActiveSheet.Shapes.AddChart2(240, xlXYScatterSmooth).Select
ActiveChart.SetSourceData Source:=Range( _
"$A$20:$A$54,$C$20:$D$54")
This is because "ActiveSheet" is VBA syntax, not syntax that excel chart settings will recognise.
B. If that doesn't work, you may need a few more steps in your code. For example:
Dim oNewChart As ChartObject
Dim sCurrentSheetName$, sSourceRange$, sFullRange$
sSourceRange = "$A$20:$A$54,$C$20:$D$54"
sCurrentSheetName = ActiveSheet.Name
sFullRange = sCurrentSheetName & "!" & sSourceRange
Set oNewChart = ActiveSheet.Shapes.AddChart2(240, xlXYScatterSmooth)
oNewChart.Chart.SetSourceData Source:=sFullRange
I have not tested the above code. If it errors on the last line, try removing the ".Chart" from the middle of that line.
ActiveSheet
in the code above to Sheets(sCurrentSheetName)
Upvotes: 1