我想使用VBA在Excel工作表中绘制多系列图表。
我想将这些数据添加到两个系列中。
Series1-> A1:B2和Series2-> A3:B4(X轴上为A,Y轴上为B)
A B
1个测试1 10
2测试2 20
3测试11 30
4测试22 40
我添加了以下代码,但遇到“无效参数”错误
Dim ochart As Object, ochartObj As Object
Set ochartObj = ActiveSheet.ChartObjects.Add(Top:=10, left:=325, Width:=600, Height:=300)
Set ochart = ochartObj.Chart
ochart.ChartType = xlXYScatter
ochart.SeriesCollection(1).XValues = Range("B1:B2")
ochart.SeriesCollection(1).Values = Range("A1:A2")
ochart.SeriesCollection(2).XValues = Range("B3:B4")
ochart.SeriesCollection(2).Values = Range("A3:A4")
请帮助:)谢谢!
答案 0 :(得分:0)
Dim ochart As Object, ochartObj As Object
Set ochartObj = ActiveSheet.ChartObjects.Add(Top:=10, left:=325, Width:=600, Height:=300)
Set ochart = ochartObj.Chart
ochart.ChartType = xlXYScatter
ochart.SeriesCollection.NewSeries
ochart.SeriesCollection.NewSeries
ochart.SeriesCollection(1).XValues = Range("B1:B2")
ochart.SeriesCollection(1).Values = Range("A1:A2")
ochart.SeriesCollection(2).XValues = Range("B3:B4")
ochart.SeriesCollection(2).Values = Range("A3:A4")
但是您确实应该:
Dim ochart As Excel.Chart, ochartObj As Excel.ChartObject
答案 1 :(得分:0)
您需要为每个系列创建一个新系列,然后为其分配值...
Dim ochart As Object, ochartObj As Object
Set ochartObj = ActiveSheet.ChartObjects.Add(Top:=10, Left:=325, Width:=600, Height:=300)
Set ochart = ochartObj.Chart
ochart.ChartType = xlXYScatter
ochart.SeriesCollection.NewSeries
ochart.SeriesCollection(1).XValues = Range("B1:B2")
ochart.SeriesCollection(1).Values = Range("A1:A2")
ochart.SeriesCollection.NewSeries
ochart.SeriesCollection(2).XValues = Range("B3:B4")
ochart.SeriesCollection(2).Values = Range("A3:A4")
此外,我建议您将对象声明为它们的特定类型。它使代码更有效率,您将受益于IntelliSense。因此,您的代码可以按如下方式重写...
Dim ochart As Chart, ochartObj As ChartObject, oSeries As Series
Set ochartObj = ActiveSheet.ChartObjects.Add(Top:=10, Left:=325, Width:=600, Height:=300)
Set ochart = ochartObj.Chart
With ochart
.ChartType = xlXYScatter
Set oSeries = .SeriesCollection.NewSeries
With oSeries
.XValues = Range("B1:B2")
.Values = Range("A1:A2")
End With
Set oSeries = .SeriesCollection.NewSeries
With oSeries
.XValues = Range("B3:B4")
.Values = Range("A3:A4")
End With
End With
希望这会有所帮助!