我正在使用以下代码:
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 =
的每个实例上,代码在建立变量时出错。为了充分建立这条线,我错过了什么?
我将with
语句用作set
变量的原因是因为使用ActiveChart
和ActiveSheet
会在旧版本的Excel中引发方法错误。
答案 0 :(得分:1)
问题是myCht
是ChartObject
对象而不是Chart
对象。因此,您需要通过图表对象的图表方法来获取图表的元素,例如与系列相关的趋势线:
Set oTren = myCht.Chart.SeriesCollection(1).Trendlines(1)