问题
I have defined a named using the following code:
ActiveWorkbook.ActiveSheet.Names.Add Name:="BCLabel", RefersToR1C1:= _
"=OFFSET(R46C3,1,0,COUNTA(R46C3:R69C3)-2)"
ActiveWorkbook.ActiveSheet.Names("BCLabel").Comment = ""
This code repeats for several worksheets, such that I have many named ranges titled BCLabel, although this refers to different ranges. For example
=OFFSET('January'!$C$46,1,0,COUNTA('January'!$C$46:$C$69)-2)
=OFFSET('February'!$C$46,1,0,COUNTA('February'!$C$46:$C$69)-2)
=OFFSET('March'!$C$46,1,0,COUNTA('March'!$C$46:$C$69)-2)
I would like to code the creation of a chart in each of these worksheets that references the correct named range. I have attempted the following code:
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.Name = "BCChart"
ActiveChart.SeriesCollection(1).Values = _
"==BCLabel"
ActiveChart.SeriesCollection(2).Values = _
"==BCLabel"
However this does not work: "==BCLabel" does not reference to the correct named range, nor does "==ActiveSheet.BCLabel". I would appreciate any assistance.
As an aside I have also encountered an error with the ActiveChart.Name = "BCChart" line.
Thanks for the help!
回答1:
Try to use following code (this works for me):
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.SeriesCollection(1).Values = Range("BCLabel")
ActiveChart.SeriesCollection(2).Values = Range("BCLabel")
Btw it's better to avoid Select
and Active...
statements. So, I rewrote your code as follows:
Sub test()
Dim ws as Worksheet
Dim sh As Shape
Set ws = Worksheets("Sheet1")
Set sh = ws.Shapes.AddChart
With sh.Chart
.ChartType = xlColumnClustered
.SeriesCollection(1).Values = ws.Range("BCLabel")
.SeriesCollection(1).Values = ws.Range("BCLabel")
End With
End Sub
About error in line ActiveChart.Name = "BCChart"
, you can see in this article, that it's read-only property for chart objects
来源:https://stackoverflow.com/questions/21135226/vba-referencing-named-range