将VBA中的图表范围设置为变量

时间:2018-01-02 19:17:02

标签: excel vba

我正在尝试设置一个范围变量,然后使用此范围变量作为Excel图表的来源。但是当我在Set rng =

运行我的宏时,我收到了对象所需的错误
 Sub temp3()
'
' temp3 Macro
'
    Dim rng As Range
    Range("A1").Select
    Range(Selection, Selection.End(xlDown)).Select
    Set rng = Range(Selection, Selection.End(xlToRight)).Select

    ActiveSheet.Shapes.AddChart2(332, xlLineMarkers).Select
    ActiveChart.SetSourceData Source:=rng
End Sub

2 个答案:

答案 0 :(得分:2)

请勿使用.Select

 Sub temp3()
'
' temp3 Macro
'
    Dim rng As Range
    Dim shp As Chart
    With Worksheets("Sheet1") 'Change to your sheet
        Set rng = .Range("A1", .Range("A1").End(xlDown).End(xlToRight))

        Set shp = Charts.Add
        Set shp = shp.Location(Where:=xlLocationAsObject, Name:=.Name)
        With shp
            .ChartType = xlLineMarkers
            .SetSourceData rng
        End With
    End With
End Sub

答案 1 :(得分:0)

您还可以创建命名范围并将图表的数据源设置为命名范围。然后您将使用 vba 更改命名范围的范围。这种方法可能更简单。请参阅 How do I redefine a named range with VBA? 了解如何更改 vba 的命名范围