使用新系列向图表 (VBA) 添加平均线时,应用程序定义或对象定义错误

问题描述

之后我有一个数据系列来创建图表,必须添加一条平均线,在“ActiveChart.FullSeriesCollection(2).Name = ycord”行出现错误为“应用程序定义或对象定义错误”,已检查并且正在创建新系列

Worksheets(sht).Activate

ycord = "=" & sht & "!$BF$" & cellposition
ydata = "=" & sht & "!$BF$" & cellposition + 1 & ":$BF$" & cellposition + 2 & ""
xdata = "=" & sht & "!$BE$" & cellposition + 1 & ":$BE$" & cellposition + 2 & ""

Range("A" & rowno & ":AF" & rowno).Select
ActiveSheet.Shapes.AddChart2(227,xlLine).Select
ActiveChart.SetSourceData Source:=Range("'" & sht & "'!$A$" & rowno & ":$AF$" & rowno)
ActiveChart.SetElement (msoElementDataLabelTop)
ActiveChart.ApplyDataLabels
ActiveChart.FullSeriesCollection(1).DataLabels.Select
Application.CommandBars("Format Object").Visible = False
ActiveSheet.ChartObjects("Chart 1").Activate

ActiveChart.PlotArea.Select
ActiveChart.ChartArea.Select
ActiveChart.ChartType = xlXYScatterSmoothNoMarkers
ActiveChart.PlotArea.Select
Application.CutcopyMode = False
Application.CutcopyMode = False
Application.CutcopyMode = False
Application.CutcopyMode = False
ActiveChart.SeriesCollection.NewSeries


//receiving the error in below line at name


ActiveChart.FullSeriesCollection(2).Name = ycord
ActiveChart.FullSeriesCollection(2).XValues = ydata
ActiveChart.FullSeriesCollection(2).Values = xdata
With ActiveChart
  .Parent.Left = Range(chartcol & chartrow).Left
  .Parent.Top = Range(chartcol & chartrow).Top
End With

解决方法

感谢 simons 评论发现工作表名称中存在空格问题,更正了空格并且代码很好