我正在尝试设置一个范围变量,然后使用此范围变量作为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
答案 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 的命名范围