Excel中如何实现每N个单元格行数据自动生成对应图表
Excel VBA 批量按分组生成图表实现方案
你可以通过循环逻辑替换硬编码的分组规则,实现全自动批量生成图表,优化后代码如下:
Sub BatchGenerateCharts() Dim startRow As Long, groupSize As Long, totalRow As Long Dim currentRow As Long, endRow As Long Dim chartObj As ChartObject Dim chartTopPos As Double ' 可自定义参数 startRow = 3 ' 数据起始行 groupSize = 29 ' 每组数据条数 chartTopPos = 10 ' 第一个图表距离顶部的距离 ' 自动计算D列最后一行有数据的行号 totalRow = Cells(Rows.Count, "D").End(xlUp).Row ' 循环处理每一组数据 For currentRow = startRow To totalRow Step groupSize endRow = currentRow + groupSize - 1 ' 避免最后一组不足29条时超出数据范围 If endRow > totalRow Then endRow = totalRow ' 添加折线图 Set chartObj = ActiveSheet.ChartObjects.Add(Left:=100, Width:=600, Top:=chartTopPos, Height:=300) chartObj.Chart.ChartType = xlLine ' 设置数据源和系列属性 With chartObj.Chart .SetSourceData Source:=Range("Sheet1!$D$" & currentRow & ":$D$" & endRow) .FullSeriesCollection(1).Name = "=""Marginal Costs""" .FullSeriesCollection(1).XValues = "=Sheet1!$C$" & currentRow & ":$C$" & endRow End With ' 下一个图表位置向下偏移,避免重叠 chartTopPos = chartTopPos + 320 Next currentRow ' 清理对象 Set chartObj = Nothing MsgBox "图表生成完成,共生成" & WorksheetFunction.RoundUp((totalRow - startRow + 1) / groupSize, 0) & "个图表" End Sub
可调参数说明
- 你可以根据实际数据调整
startRow(数据起始行)、groupSize(每组数据条数) - 可以修改
ChartObjects.Add里的Width、Height参数调整图表尺寸,修改位置偏移量320调整图表之间的间距 - 如果需要更换图表类型,修改
xlLine为对应的图表类型常量即可
内容的提问来源于stack exchange,提问作者Gauri Sharma
相关产品推荐
相关产品推荐

