如何在VBA中使用循环创建不确定数量的图表

时间:2019-07-11 18:12:44

标签: excel vba loops charts

我在电子表格中存储了不确定年份的数据。我拥有的数据在imgur屏幕截图中进行了布局。目前,我有3年的数据(2016年至2018年),但是我希望我的代码能够无限期地工作,因为我将其用于具有多年数据的数据集。我想每年将这些数据分成三个图表:平均疾病风险####,平均疾病成本####,平均生物特征识别####。我希望这些图表可以显示在同一电子表格中,数据按三列排列并逐年递增。

https://imgur.com/a/pO2ux7j

下面的代码仅适用于平均疾病风险####图形。

Sub ChartMake()

Dim ChartCount As Integer
ChartCount = ActiveSheet.ChartObjects.Count

If ChartCount > 0 Then
ActiveSheet.ChartObjects.Delete
End If

Dim NLoops As Integer, LoopNumber As Integer

NLoops = Worksheets("Data Input").Range("Q2").Value - 1

LoopNumber = 1

Dim cht As ChartObject, rngChart As Range, destinationSheet As String, Results As Worksheet, StartRow As Integer, EndRow As Integer, StartChart As Integer, EndChart As Integer

Set Results = Worksheets("Results")

destinationSheet = ActiveSheet.Name

Do While NLoops >= 0

StartRow = NLoops * 27
EndRow = NLoops * 27 + 5
StartChart = NLoops * 9 + 9
EndChart = NLoops * 9 + 17

Set co = Sheets("Results").ChartObjects.Add(6, StartChart, 5, 8)
ActiveSheet.ChartObjects(1).Activate
ActiveChart.SetSourceData Source:=Results.Range(Results.Cells(StartRow, "A"), Results.Cells(EndRow, "B"))
ActiveChart.ChartType = xlColumnClustered
ActiveChart.ChartTitle.Format.TextFrame2.TextRange.Font.Fill.ForeColor.RGB = RGB(72, 72, 72)
ActiveChart.Axes(xlCategory).TickLabels.Font.Color = RGB(72, 72, 72)
ActiveChart.Axes(xlValue).TickLabels.Font.Color = RGB(72, 72, 72)
ActiveChart.SeriesCollection(LoopNumber).Points(1).Interior.Color = RGB(59, 110, 172)
ActiveChart.SeriesCollection(LoopNumber).Points(2).Interior.Color = RGB(59, 110, 172)
ActiveChart.SeriesCollection(LoopNumber).Points(3).Interior.Color = RGB(59, 110, 172)
ActiveChart.SeriesCollection(LoopNumber).Points(4).Interior.Color = RGB(59, 110, 172)
ActiveChart.SeriesCollection(LoopNumber).Format.Shadow.Visible = msoTrue
Set cht = ActiveChart.Parent
With cht
.Left = Results.Cells(StartChart, "F").Left
.Top = Results.Cells(StartChart, "F").Top
.Height = Results.Range(Results.Cells(StartChart, "F"), Cells(EndChart, "J")).Height
.Width = Results.Range(Results.Cells(StartChart, "F"), Cells(EndChart, "J")).Width
End With
ActiveChart.Legend.Select
Selection.Delete

NLoops = NLoops - 1

LoopNumber = LoopNumber + 1

Loop

End Sub

当代码循环时,它会将源数据重新分配到下一个循环的年份,并也移到下一年的位置(2018年的图实际上变成了2017年的图)。我认为这与我制作图表或图表对象或使用ActiveChart的方式有关。

如何每次都制作一个新图表?我不知道如何无限期地为每个循环创建一个新的图表对象。

0 个答案:

没有答案