我想在excel宏中创建折线图。我在excel中有下表。
第一个折线图包含单元格A和B的值范围。第二个折线图包含单元格A和C的值范围。第三个折线图包含单元格A和D的值范围。
ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range("A1:D3")
ActiveChart.ApplyDataLabels
ActiveChart.ChartType = xlLine
以上代码仅生成范围A1至D4的一个折线图。
答案 0 :(得分:3)
这是一个很好的问题,宏录制器可以提供如何回答的良好提示。您只需要定义另一个系列集合。以下是宏录制器无需修改即可生成的内容。
Sub Macro1()
Range("A1:D2").Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlLine
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$1:$D$2")
ActiveChart.PlotArea.Select
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(2).Name = "=Sheet1!$A$3"
ActiveChart.SeriesCollection(2).Values = "=Sheet1!$B$3:$D$3"
End Sub
以下是我不使用select
的方法Sub createChart()
Dim wks As Worksheet
Set wks = Worksheets("Sheet1")
Dim chrt As Chart
Set chrt = wks.Shapes.AddChart.Chart
With chrt
.ChartType = xlLine
.SetSourceData Source:=Range("Sheet1!$A$1:$D$2")
.SeriesCollection.NewSeries
.SeriesCollection(2).Name = "=Sheet1!$A$3"
.SeriesCollection(2).Values = "=Sheet1!$B$3:$D$3"
End With
End Sub
<强>循环强>
Sub createChartWithLoop()
Dim wks As Worksheet
Set wks = Worksheets("Sheet1")
Dim chrt As Chart
Set chrt = wks.Shapes.AddChart.Chart
Dim chartRange As Range
Set chartRange = wks.Range("A1:A4")
With chrt
.ChartType = xlLine
.SetSourceData Source:=Range(wks.Range("A" & chartRange.Row & ":D" & chartRange.Row).Address)
For i = chartRange.Row + 1 To chartRange.Rows.Count
.SeriesCollection.NewSeries
.SeriesCollection(i).Name = wks.Cells(i, 1)
.SeriesCollection(i).Values = wks.Range("B" & i & ":D" & i)
Next i
End With
End Sub
编辑 - 从每个行数据创建不同的图表
Sub createDifferentCharts()
Dim wks As Worksheet
Set wks = Worksheets("Sheet1")
Dim chartRange As Range
Set chartRange = wks.Range("A1:A4")
For i = chartRange.Row To chartRange.Rows.Count
With wks.Shapes.AddChart.Chart
.ChartType = xlLine
.SetSourceData Source:=Range(wks.Range("A" & i & ":D" & i).Address)
.Parent.Left = 20 + i * 50
.Parent.Top = 40 + i * 50
End With
Next i
End Sub
结果:
为每个列数据创建不同的图表,其中A列为标签:
Sub createDifferentCharts()
Dim wks As Worksheet
Set wks = Worksheets("Sheet1")
Dim chartRange As Range
Set chartRange = wks.Range("A1:D4")
For col = chartRange.Column + 1 To chartRange.Columns.Count
With wks.Shapes.AddChart.Chart
.ChartType = xlLine
.SetSourceData Source:=Range(wks.Cells(1, 1).Address)
.SetSourceData Source:=wks.Range("A1:A4," & Range(Cells(chartRange.Row, col), Cells(chartRange.Rows.Count, col)).Address)
.Parent.Left = col * 30
.Parent.Top = col * 30
End With
Next col
End Sub