使用VBA创建包含多个工作表数据的图表

时间:2014-06-12 23:32:33

标签: excel vba excel-vba charts

我只是尝试:使用VBA创建包含多张图表数据的图表。

在我的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或/在excel中),但我不明白是什么导致了这个问题。

如果您有任何线索,请告诉我:)

提前致谢,Jelle

1 个答案:

答案 0 :(得分:1)

这对我有用(在我的情况下略有不同的设置)

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