我正在尝试将多个系列动态添加到折线图中。我事先不知道有多少系列,所以它需要是动态的。我想出但不起作用的是以下内容:
工作表 ActiveSheet(或 Sheets("Data"))具有从 C14 到 Cend 的行,其中包含从 E14:Eend 到 R14:Rend 的 XValue 和列,其中“end”标记由 C 列确定的最后一行数据。系列名称存储在第 9 行。所有系列的 XValue 都相同。
我的大问题是,我找不到将所有数据列作为系列动态添加到我的图表以及相应名称的方法。我不是 VBA 专家,所以请善待。我已经阅读了各种资源并尝试了许多脚本,但似乎没有一个有效。对象目录有点帮助,但是我的问题仍然存在。
Sub MakeChart()
Dim LastColumn As Long
Dim LastRow As Long
Dim i As Integer
Dim u As Integer
Dim NameRng As String
Dim CountsRng As Range
Dim xRng As Range
LastColumn = ActiveSheet.Cells(8, Columns.Count).End(xlToLeft).Column
ColumnCount = LastColumn - 4
LastRow = ActiveSheet.Range("C" & ActiveSheet.Rows.Count).End(xlUp).Row
' Debug.Print ("Last Column: " & LastColumn & " Count: " & ColumnCount & " LastRow: " & LastRow)
Charts.Add
With ActiveChart
.ChartType = xlLineMarkers
.HasTitle = True
.ChartTitle.Text = "Test"
End With
For i = 1 To ColumnCount
u = i + 4
NameRng = Sheets("Data").Range("R9:C" & u).Value
Set xRng = Sheets("Data").Range("R14:C3", "R" & LastRow & ":C3")
Set CountsRng = Sheets("Data").Range("R14:C" & u, "R" & LastRow & ":C" & u)
' Debug.Print ("CountsRng: R14:C" & u & ", R" & LastRow & ":C" & u & " NameRng: " & NameRng & " xRng: R14:C3 , R" & LastRow & ":C3")
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(i).XValues = xRng
ActiveChart.SeriesCollection(i).Values = CountsRng
ActiveChart.SeriesCollection(i).Name = NameRng
Next i
End Sub