4

I have a sheet with a chart in it. I need to insert a button to TOGGLE the Trendline On/Off. So first, I need to check whether a trendline exists or not. Sounds simple, but is driving me NUTS!!!

Here is the code that I use to create the trednline and format it:

Sub Trending() 

Sheets("Sheet1").ChartObjects(1).Activate
    ActiveChart.SeriesCollection(1).Trendlines.Add
    ActiveChart.SeriesCollection(1).Trendlines(1).Select
    With Selection
        .Type = xlPolynomial
        .Order = 3
        .Border.ColorIndex = 3
        .Border.Weight = xlMedium

    End With

End Sub

To check for the existence of a trendline, I tried:

If Sheets("Sheet 1").ChartObjects(1).SeriesCollections(1).Trendlines(1).Count = 1 Then
    [Statement]
End If

But the test fails.

What am I doing wrong? What is a non-dirty way to do it?

Thanks, Al

4

1 回答 1

6

If你的说法有三处不对。如果你把你的陈述分解成更小的部分并分别测试它们,你会发现:

  1. Sheet1,不是Sheet 1。没有空间。这就是导致“下标超出范围”错误的原因。
  2. SeriesCollection属性适用于Chart对象,而不是ChartObject对象。是的,我知道这个愚蠢的 Excel 术语令人困惑。Anyhoo,你需要ChartObjects(1).Chart.SeriesCollection(1),而不是ChartObjects(1).SeriesCollection(1)
  3. Trendlines(1)返回一个Trendline对象,这是不Count能够的。您想计算趋势线集合中的项目,即Trendlines.Count,不是Trendlines(1).Count

总结一下,就是这样写的:

If Sheets("Sheet1").ChartObjects(1).Chart _
    .SeriesCollection(1).Trendlines.Count > 1 Then
    MsgBox "there is exactly one trendline"
End If

注意:这仅在趋势线计数正好为 1 时才有效。如果可能有多个,请考虑替换=为。>=

于 2012-04-30T16:37:22.597 回答