Excel VBA adding data to a chart

chartsexcelvba

Hello I have a little question for adding data to an existing chart.

Now I have a worksheet containing a data series with months for the years in the 2nd row of the sheet. So the months are for example B2 1.2017, C2 2.2017, and in the rows 3,4,5,6,7 and 8 there is always data for that month.

Now I just want my macro to add the new Month plus the data of the rows below to my existing chart.

the code I have so far is this:

Worksheets("Summary").ChartObjects("Chart").Activate
   ActiveChart.SeriesCollection.Add _
   Source:=Worksheets("Summary").Range("B2:B8")

now this does just create new data series but there is actually no new data added to the chart.

Best Answer

The code below might seem a little long, but it's the safest way to add a new Series with Data to an existing Chart.

I'm setting all the necessary Objects so the code will be as "safe-proof" as can be.

Code

Option Explicit

Sub AddSeriestoChart()

Dim ws As Worksheet
Dim ChtRng As Range
Dim ChtObj As ChartObject
Dim Ser As Series

' set the Worksheet object
Set ws = ThisWorkbook.Worksheets("Summary")

' Set the Chart Object
Set ChtObj = ws.ChartObjects("Chart")

' Set the Range of the Chart's source data
Set ChtRng = ws.Range("B2:B8")

With ChtObj
    ' add a new series to chart
    Set Ser = .Chart.SeriesCollection.NewSeries

    ' set the source data of the new series
    Ser.Values = "=" & ChtRng.Address(False, False, xlA1, xlExternal)
End With

End Sub

Edit 1: to modify existing Series data, use something like the code below :

With ChtObj          
    For i = 1 To .Chart.SeriesCollection.Count
        Set Ser = .Chart.SeriesCollection(i)

        ' set the source data of the new series
        Set ChtRng = ws.Range("B" & i + 2)
        Ser.Values = "=" & ChtRng.Address(False, False, xlA1, xlExternal)

        Set ChtRng = Nothing
    Next i
End With