Add Trendline if none exists

36 Views Asked by At

I have created the following code to format a chart. Now I only want to add a trendline if none exists yet. How do I do this or where is my mistake? I am sure that I am missing something obvious

Sub FormatChart_A()
   Dim serReihe As series
                    With ActiveSheet.ChartObjects("test_A").Chart
                        For Each serReihe In .SeriesCollection
                            If InStr(serReihe.Name, "value_A") > 0 Then
                                serReihe.ChartType = 65
                                serReihe.Border.Color = RGB(165, 79, 255)
                            ElseIf InStr(serReihe.Name, "value_B") > 0 Then
                                serReihe.ChartType = 65
                                serReihe.Border.Color = RGB(79, 225, 235)
                                .SeriesCollection(2).AxisGroup = 2
                            ElseIf .SeriesCollection(serReihe.Name, "value_B").Trendlines.Count = 0 Then
                                .SeriesCollection(1).Trendlines.Add Type:=xlLinear, Name:="Trend Flächenleistung"
                            End If
                        Next serReihe
                    End With
End Sub
1

There are 1 best solutions below

2
On

If you already know the name of the series, you can simply use:

If .SeriesCollection("Value_B").Trendlines.Count = 0 Then
    .SeriesCollection("Value_B").Trendlines.Add Type:=xlLinear, Name:="Trend Flächenleistung"
End If

There is no need to iterate through the series to do this.