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
There are three things wrong with your
Ifstatement. Had you broken down your statement in smaller bits and tested each of them separately, you would have found that:Sheet1, notSheet 1. No space. This is what causes your “Subscript is out of range” error.SeriesCollectionproperty applies toChartobjects, notChartObjectobject. Yes, I know this stupid Excel terminology is confusing. Anyhoo, you needChartObjects(1).Chart.SeriesCollection(1), notChartObjects(1).SeriesCollection(1).Trendlines(1)returns aTrendlineobject, which is notCountable. You want to count the itemts in the trendlines collection, i.e.Trendlines.Count, notTrendlines(1).Count.To summarise, this is how to write it:
Note: this will only work if the trendline count is exactly one. Consider replacing
=with>=if there may be more than one.