提问人:Alessandro Mueller 提问时间:10/5/2023 最后编辑:Alessandro Mueller 更新时间:10/19/2023 访问量:49
VBA - 如何创建多个图表工作表,每个系列一个
VBA - how to create multiple Chart Sheets, one for each series
问:
我是使用 VBA 编码的新手,可以使用您的帮助!
我有以下数据集。我有很多区域,我想在自己的图表表中分别显示每个区域的数据。
年 | 区域 1 | 区域 2 | 区域 3 |
---|---|---|---|
2017 | 10 | 60 | 70 |
2018 | 20 | 50 | 80 |
2019 | 30 | 40 | 90 |
以下简单代码允许我创建预期的图表表,但仅适用于一个数据系列:Sheet(“Data_Source”) 中的数据系列。范围 (B1:B8)。
Sub Add_Chart_Tab()
Dim MyChart As Chart
Set MyChart = Charts.Add
With MyChart
.SetSourceData Source:=Sheets("Data_Source").Range("B1:B8")
.SeriesCollection(1).XValues = "=Data!$A$2:$A$8"
End With
End Sub
我尝试了另一种代码,它为我提供了我想要的东西,除了 1) 图表都一个接一个地藏在同一张工作表中,以及 2) 这些是图表而不是图表工作表。在上面的代码中,我想将源(“B1:B8”)中的范围设置为变量单元格(如下面的代码中所示,带有 i 和 j),但每次尝试时,我都会收到一条错误消息,指出不支持此方法。
Sub AddCharts()
Dim i As Integer ' rows
Dim j As Integer ' columns
i = Cells(Rows.Count, 1).End(xlUp).Row
For j = 2 To 4
With ActiveSheet.Shapes.AddChart.Chart
.ChartType = xlLine
.SeriesCollection.NewSeries
With .SeriesCollection(1)
.Name = "=" & ActiveSheet.Name & "!" & Cells(1, j).Address
.XValues = "=" & ActiveSheet.Name & "!" & Range(Cells(2, 1), Cells(i, 1)).Address
.Values = "=" & ActiveSheet.Name & "!" & Range(Cells(2, j), Cells(i, j)).Address
End With
End With
Next j
End Sub
我的目标是将这两个代码结合起来:
- 创建多个图表表,而不是普通图表
- 遍历数据系列,以便在每个图表工作表中显示一个区域的数据
有人可以帮我吗?
答:
0赞
taller
10/6/2023
#1
图表的参数 (, ) 有可能成为动态对象。SetSourceData
XValues
Range
Microsoft 参考文档:
Option Explicit
Sub AddCharts()
Dim MyChart As Chart
Dim i As Integer, Dim j As Integer
Dim Sht As Worksheet
Set Sht = Sheets("Data")
i = Sht.Cells(Sht.Rows.Count, 1).End(xlUp).Row
For j = 2 To 4
Set MyChart = Charts.Add(after:=Sheets(Sheets.Count))
With MyChart
.SetSourceData Source:=Sht.Cells(2, j).Resize(i - 1, 1)
.SeriesCollection(1).XValues = Sht.Range("A2").Resize(i - 1, 1)
.Name = Sht.Cells(1, j)
End With
Next j
End Sub
0赞
Jon Peltier
10/19/2023
#2
这应该可以帮助您入门。
Sub Add_Chart_Tabs()
Dim XVals As Range
Set XVals = Worksheets("Data").Range("A2:A8")
Dim iChart As Long
For iChart = 1 To 3 ' or however many
Dim YVals As Range
Set YVals = XVals.Offset(, iChart)
Dim SrsName As Range
Set SrsName = YVals.Offset(-1).Resize(1)
Dim MyChart As Chart
Set MyChart = Charts.Add
With MyChart
Dim iSrs As Long
For iSrs = .SeriesCollection.Count To 1 Step -1
' remove any series created by default
.SeriesCollection(iSrs).Delete
Next
With .SeriesCollection.NewSeries
.Values = YVals
.XValues = XVals
.Name = "=Data!" & SrsName.Address
End With
End With
Next
End Sub
评论