I am a new user on Excel VBA, recently i encounter this error when ever i try to run my macro. What my macro do is by reading the cell row data and will create a chart by itself for export purpose, etc.
Below is my macro code
Sub CombinationChart()
Dim lastrow As String
Dim boundaryRow As String
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
lastrow = mySheet.Range("A" & Rows.Count).End(xlUp).Row
boundaryRow = lastrow - 20
ActiveChart.SetSourceData Source:=Range("mySheet!$A$" & boundaryRow ":$B$" & lastrow) 'make sure the range is correct here
ActiveChart.FullSeriesCollection(1).ChartType = xlLine 'select which column should be the Line or the Column
ActiveChart.FullSeriesCollection(1).AxisGroup = 1
End Sub
The error part is here
ActiveChart.SetSourceData Source:=Range("mySheet!$A$" & boundaryRow ":$B$" & lastrow) 'make sure the range is correct here
My last row variable is the last row which contains data in the excel table whereas boundaryRow is a variable who gets the last row value and subtract it by 20 which is last row - 20, but i just cant look for a way to put in my two variables into my ActiveChart.Range.
You have missed the concatenate operator ( &
) in your problem line.
Here is how it should look:
ActiveChart.SetSourceData Source:=Range("mySheet!$A$" & boundaryRow & ":$B$" & lastrow)
&
was missing between boundaryRow
and ":$B$"
Here's how to do what you want with a Range
object variable. I'm assuming here - since you use it to calculate lastRow
- that you have mySheet
defined as a Worksheet
object (probably globally).
Sub CombinationChart()
Dim lastrow As Long
Dim boundaryRow As Long
Dim chartData as Range
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
lastrow = mySheet.Range("A" & Rows.Count).End(xlUp).Row 'mySheet is defined elsewhere
boundaryRow = lastrow - 20
Set chartData = mySheet.Cells(boundaryRow,1).Resize(21,2) ' 21 rows x 2 columns
ActiveChart.SetSourceData Source:=chartData 'make sure the range is correct here
ActiveChart.FullSeriesCollection(1).ChartType = xlLine 'select which column should be the Line or the Column
ActiveChart.FullSeriesCollection(1).AxisGroup = 1
End Sub
You could do this "on the fly" too, substituting in the expression I have assigned to chartData
to the SetSourceData
Source
parameter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.