excel - 使用 VBA 的动态多重图表
问题描述
我尝试使用 VBA 创建动态图表,例如我有 5 个学生我需要创建 5 个图表
对于每个学生。
Sub Macro4()
Rows("2:2").Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.SetSourceData Source:=Range("Sheet1!$2:$2")
Rows("3:3").Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.SetSourceData Source:=Range("Sheet1!$3:$3")
Rows("4:4").Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.SetSourceData Source:=Range("Sheet1!$4:$4")
Range("D12").Select
ActiveWorkbook.Save
End Sub
我使用宏创建这个只是为了测试,但我尝试动态地这样做,因为如果我有超过 100 名学生,这将是困难的,等等。
我希望你们帮助我
谢谢
解决方案
请尝试下一个方法。无需任何选择。选择没用,它只消耗 Excel 资源:
Sub AddCharts()
Dim sh As Worksheet, ch As Shape, chartNo As Long
Dim prevWith As Long, i As Long
Set sh = ActiveSheet 'the sheet where the charts to be created
'chartNo = 5
chartNo = = Worksheets("Sheet1").Range("A" & rows.count).End(xlUp).row - 1
For i = 1 To chartNo
Set ch = sh.Shapes.AddChart
ch.Chart.ChartType = xlColumnClustered
ch.Chart.SetSourceData Source:=Range("Sheet1!$" & i + 1 & ":$" & i + 1)
ch.Chart.Parent.left = sh.Range("A1").left + prevWith 'here the first left chart position to be set
prevWith = ch.Chart.Parent.width 'the chart width, the next one will be added to its right side
Next i
ActiveWorkbook.Save
End Sub
推荐阅读
- sql - SQL 从标签中的 XML 获取值,按标签值
- javascript - 根据给定的索引数组返回数组中的一些成员
- microsoft-graph-api - callRecord POST 类型的 Microsoft Graph 订阅有效,但 GET 失败并出现错误 ExtensionError
- linux - 虚拟框不允许我打字。[拱形 Linux]
- ios - Swift 图像从其帧的底部到顶部出现动画(擦除动画)
- flutter - [Flutter]如何从图库中动态导入图片
- python - 想要使用 python 正则表达式读取下面文本中“# HCI Command”和“#---------------”之间的内容
- android - 我如何用一种颜色为我的 CircleAvatar 的一半着色,而另一半用另一种颜色着色
- selenium - 附件(注释@Step,@Screenshot)在运行可执行jar文件时没有保存在诱惑结果中
- javascript - 我如何使用来自 node.js 中另一个页面的承诺