将趋势线设置为variables会引发错误

我正在与他合作下面的代码:

Sub AddTrendLinesBoth() Dim myCht As ChartObject Dim oTren As Trendline Dim oWb As Workbook Dim oWS As Worksheet Set oWb = ThisWorkbook Set oWS = oWb.Sheets("Summary") Set myCht = oWS.ChartObjects("Chart 1") On Error GoTo GetOut With myCht.Chart .SeriesCollection(1).Trendlines.Add .SeriesCollection(2).Trendlines.Add End With Set oTren = myCht.SeriesCollection(1).Trendlines(1) With oTren.Format.Line .Visible = msoTrue .Weight = 3 .ForeColor.RGB = RGB(112, 48, 160) .Transparency = 0 End With Set oTren = myCht.SeriesCollection(2).Trendlines(1) With oTren.Format.Line .Visible = msoTrue .Weight = 3 .ForeColor.RGB = RGB(255, 0, 0) .Transparency = 0 End With GetOut: End Sub 

set oTren =每个实例set oTren =在build立variables时的代码错误。 我错过了什么来充分确定这条线? 我使用语句作为setvariables的原因是因为使用ActiveChartActiveSheet抛出旧版本的Excel方法错误。

问题是myChtChartObject对象而不是Chart对象。 因此,您需要通过图表对象的图表方法来获取图表的元素,例如与系列相关的趋势线:

 Set oTren = myCht.Chart.SeriesCollection(1).Trendlines(1)