VBA与Excel进阶系列-03-图表(下篇)
系统:Windows 7
软件:Excel 2010
- 这个系列作为入门篇的下一篇,稍微进阶一下,嘿嘿
- 今天继续
VBA
对图表的操作,百分比堆积柱形图作为示例- 扩充了一些关于轴的设置,以及分类间距设置
Part 1:目标
- 事先调整好单元格大小,使得
A8:J15
区域不同单元格的高度相同,宽度也相同 - 根据已有数据生成百分比堆积柱形图,将其插入
A8:J15
区域 - 对柱状图的三个部分单独设置填充色及轮廓,分为红,黄,绿三个颜色
- 对图表进行设置,包括数据标签,图例,坐标轴,分类间距等
百分比堆积柱形图
最终效果
Part 2:代码
Sub test()
Set sht1 = ThisWorkbook.Worksheets("示例")
x = sht1.Range("A8").Left
y = sht1.Range("A8").Top
w = sht1.Range("A8").Width * 10
h = sht1.Range("A8").Height * 8
Set ch1 = sht1.ChartObjects.Add(x, y, w, h)
'设置数据源
ch1.Chart.SetSourceData Source:=sht1.Range("A2:G5")
'图表类型
ch1.Chart.ChartType = xlColumnStacked100
'设置1档柱状图的填充色和轮廓
Set bar1 = ch1.Chart.SeriesCollection("一档")
With bar1.Format.Fill
.Visible = msoTrue
.ForeColor.RGB = RGB(0, 176, 80)
.Transparency = 0
.Solid
End With
With bar1.Format.Line
.Visible = msoTrue
.ForeColor.RGB = RGB(0, 0, 0)
.Transparency = 0
End With
'设置2档柱状图的填充色和轮廓
Set bar2 = ch1.Chart.SeriesCollection("二档")
With bar2.Format.Fill
.Visible = msoTrue
.ForeColor.RGB = RGB(255, 192, 0)
.Transparency = 0
.Solid
End With
With bar2.Format.Line
.Visible = msoTrue
.ForeColor.RGB = RGB(0, 0, 0)
.Transparency = 0
End With
'设置3档柱状图的填充色和轮廓
Set bar3 = ch1.Chart.SeriesCollection("三档")
With bar3.Format.Fill
.Visible = msoTrue
.ForeColor.RGB = RGB(255, 0, 0)
.Transparency = 0
.Solid
End With
With bar3.Format.Line
.Visible = msoTrue
.ForeColor.RGB = RGB(0, 0, 0)
.Transparency = 0
End With
'设置可视化
ch1.Chart.SetElement (msoElementPrimaryValueGridLinesNone) ' 取消主要横网格线
ch1.Chart.SetElement (msoElementLegendBottom) ' 设置图例在底部显示
ch1.Chart.SetElement (msoElementDataLabelCenter) ' 设置数据标签居中
'设置坐标轴
ch1.Chart.Axes(xlValue).MinimumScale = 0
ch1.Chart.Axes(xlValue).MaximumScaleIsAuto = True
ch1.Chart.Axes(xlValue).MajorUnit = 0.2
'分类间距设置
ch1.Chart.ChartGroups(1).GapWidth = 82
End Sub
Part 3:部分代码解读
w = sht1.Range("A8").Width * 10
获取A8
单元格宽度的10倍h = sht1.Range("A8").Height * 8
获取A8
单元格高度的8倍,结合add
就可以控制插入图表的大小,为了显示效果,需先设置好单元格大小,使其同大小bar1.Format.Fill
对柱状图填充使用Fill
bar1.Format.Line
对柱状图轮廓使用Line
ch1.Chart.Axes(xlValue)
对坐标轴进行设置ch1.Chart.ChartGroups(1).GapWidth = 82
对其分类间距进行设置,见下图
分类间距
以上为本次的学习内容,下回见
本文为原创作品,如若转载请标明出处,如发现有错误,欢迎留言指出
更多原创请关注微信公众号
扫描二维码,关注公众号
让重复工作一键化,让时间更有意义