Search code examples
excelvbaexcel-charts

Delete data series from existing xy graph


I would like to create a code that deletes a data series from an existing xy chart on the sheet. but i dont know how what is wrong with this code. someone please help me.

Dim srs As Series
ActiveSheet.ChartObjects("Chart 1").Activate
With ActiveChart
    For Each srs In .SeriesCollection
        If .Name = c Then
        .SeriesCollection(srs).Delete
        End If
    Next
End With

Solution

  • When you use With [Object] ... End With, all dot methods or properties in effect will be appended to that [Object]

    With ActiveChart
        For Each srs In .SeriesCollection
            If .Name = c Then
            .SeriesCollection(srs).Delete
            End If
        Next
    End With
    

    In effect, that will become:

    For Each srs In ActiveChart.SeriesCollection
        If ActiveChart.Name = c Then
             ActiveChart.SeriesCollection(srs).Delete
        End If
    Next
    

    I think ActiveChart.Name is not the intended property to compare from in your IF statement.

    You may try "srs.Name = c" in your IF and "srs.Delete" inside that like so:

    With ActiveChart
        For Each srs In .SeriesCollection
            If srs.Name = c Then
               srs.Delete
            End If
        Next
    End With
    

    Please tell me if it works.