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

时间:2016-06-15 15:30:16

标签: excel vba excel-vba

我正在使用以下代码:

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变量的原因是因为使用ActiveChartActiveSheet会在旧版本的Excel中引发方法错误。

1 个答案:

答案 0 :(得分:1)

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

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