使用VBA从多个工作表创build图表

我只是试图:使用VBA创build一个来自多个工作表的数据的图表。

在for循环中发生了一些奇怪的事情,最后每个系列都应用了相同的数据。 (而不是每个系列都显示来自相应表格的数据,谁都不同)

使用这个代码:

Private Sub CommandButton1_Click() Charts.Add ActiveChart.ChartType = xlLineStacked ActiveChart.Location Where:=xlLocationAsNewSheet, Name:="packetLoss" For i = 1 To 8 ActiveChart.SeriesCollection.NewSeries Next i For i = 1 To 8 Dim chartName As String chartName = "packetsOverTime" & (i + 3) Set xRng = Sheets(chartName).Range("B2:B1000") ActiveChart.SeriesCollection(i).Values = Sheets(chartName).Range("B2:B1000") ActiveChart.SeriesCollection(i).Name = chartName Next i End Sub 

而此代码正确显示“packetsOverTime5”的数据

 Private Sub CommandButton1_Click() Charts.Add ActiveChart.ChartType = xlLineStacked ActiveChart.Location Where:=xlLocationAsNewSheet, Name:="packetLoss" For i = 1 To 8 ActiveChart.SeriesCollection.NewSeries Next i 'this is new: just apply data from "packetsOverTime5" chartName = "packetsOverTime5" ActiveChart.SeriesCollection(i).Values = Sheets(chartName).Range("B2:B1000") ActiveChart.SeriesCollection(i).Name = chartName End Sub 

最后一段代码与第一段代码的结果相同:

 Private Sub CommandButton1_Click() Charts.Add ActiveChart.ChartType = xlLineStacked ActiveChart.Location Where:=xlLocationAsNewSheet, Name:="packetLoss" For i = 1 To 8 ActiveChart.SeriesCollection.NewSeries Next i 'this piece is back: For i = 1 To 8 Dim chartName As String chartName = "packetsOverTime" & (i + 3) Set xRng = Sheets(chartName).Range("B2:B1000") ActiveChart.SeriesCollection(i).Values = Sheets(chartName).Range("B2:B1000") ActiveChart.SeriesCollection(i).Name = chartName Next i 'this piece doesn't have any effect now chartName = "packetsOverTime5" ActiveChart.SeriesCollection(i).Values = Sheets(chartName).Range("B2:B1000") ActiveChart.SeriesCollection(i).Name = chartName End Sub 

我有4年以上的编程经验(从来不用VBA或/擅长寿),但我不明白是什么造成这个问题。

如果你有任何线索,请让我知道:)

在此先感谢,杰勒

这工作对我来说(略有不同的设置在我的情况)

 Private Sub Tester() Dim cht As Chart, s As Series, xRng As Range Dim i As Long, chartName As String Set cht = Charts.Add cht.ChartType = xlLine cht.Location Where:=xlLocationAsNewSheet, Name:="packetLoss" For i = 1 To 3 chartName = "Sheet" & i Set xRng = Sheets(chartName).Range("A1:A10") With cht.SeriesCollection.NewSeries() .Values = xRng .Name = chartName End With Next i End Sub