VBA引用命名范围

时间:2014-01-15 10:41:58

标签: vba reference named-ranges

我使用以下代码定义了一个命名:

ActiveWorkbook.ActiveSheet.Names.Add Name:="BCLabel", RefersToR1C1:= _
    "=OFFSET(R46C3,1,0,COUNTA(R46C3:R69C3)-2)"
ActiveWorkbook.ActiveSheet.Names("BCLabel").Comment = ""

此代码重复了几个工作表,因此我有许多名为BCLabel的命名范围,尽管这指的是不同的范围。例如

=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)

我想在每个引用正确命名范围的工作表中编写图表的代码。我尝试了以下代码:

ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.Name = "BCChart"
ActiveChart.SeriesCollection(1).Values = _
    "==BCLabel"
ActiveChart.SeriesCollection(2).Values = _
    "==BCLabel"

但是这不起作用:“== BCLabel”不引用正确的命名范围,也不引用“== ActiveSheet.BCLabel”。我将不胜感激。

另外,我还遇到了ActiveChart.Name =“BCChart”行的错误。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

尝试使用以下代码(这适用于我):

ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.SeriesCollection(1).Values = Range("BCLabel")
ActiveChart.SeriesCollection(2).Values = Range("BCLabel")

顺便说一句,最好避免使用SelectActive...语句。所以,我重写了你的代码如下:

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

关于行ActiveChart.Name = "BCChart"中的错误,您可以在此article中看到它是图表对象的只读属性