Excel VBA将数据添加到图表

您好,我有一个小问题,添加数据到现有的图表。

现在我有一个工作表,其中包含一个数据系列,在工作表的第二行中有几个月。 因此,这些月份是例如B2 1.2017,C2 2.2017,并且在3,4,5,6,7和8行中总是有该月份的数据。

现在我只想让我的macros添加新的月份加上下面的行数据到我现有的图表。

我到目前为止的代码是这样的:

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

现在这只是创build新的数据系列,但实际上没有新的数据添加到图表。

下面的代码可能看起来有点长,但是将最新的Series with Data添加到现有Chart中是最安全的方法。

我正在设置所有必要的Objects所以代码将尽可能“安全”。

 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 

编辑1 :修改现有的Series数据,使用类似下面的代码:

 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 

这是我会用的

 wsMetric.ChartObjects("Chart").Chart 'This one will link data from another workbook .SeriesCollection(1).Values = "='[" & wb.Name & "]" & ws.Name & "'!$" & sCol & "$" & lRow & ":$" & sCol2 & "$" & lRow2 'Debug.Print "='[" & wb.Name & "]" & ws.Name & "'!$" & sCol & "$" & lRow & ":$" & sCol2 & "$" & lRow2 'Returns ='[Book1.xlsm]Sheet1'!$A$1:$A$11 'This one will link data from the same workbook, same or different sheet .SeriesCollection(1).Values = "=" & ws.Name & "!$" & sCol & "$" & lRow & ":$" & sCol2 & "$" & lRow 2 'Debug.print "=" & ActiveSheet.Name & "!$" & scol & "$" & lrow & ":$" & scol2 & "$" & lrow2 'Returns =Sheet1!$A$1:$A$11 End With 

这不使用。 .Activate并直接访问图表