VBA与Excel进阶系列-03-图表(下篇)

VBA与Excel进阶系列-03-图表(下篇)

系统:Windows 7
软件:Excel 2010

  • 这个系列作为入门篇的下一篇,稍微进阶一下,嘿嘿
  • 今天继续VBA对图表的操作,百分比堆积柱形图作为示例
  • 扩充了一些关于轴的设置,以及分类间距设置

Part 1:目标

  1. 事先调整好单元格大小,使得A8:J15区域不同单元格的高度相同,宽度也相同
  2. 根据已有数据生成百分比堆积柱形图,将其插入A8:J15区域
  3. 对柱状图的三个部分单独设置填充色及轮廓,分为红,黄,绿三个颜色
  4. 对图表进行设置,包括数据标签,图例,坐标轴,分类间距等

百分比堆积柱形图

这里写图片描述

最终效果
这里写图片描述

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:部分代码解读

  1. w = sht1.Range("A8").Width * 10获取A8单元格宽度的10倍
  2. h = sht1.Range("A8").Height * 8获取A8单元格高度的8倍,结合add就可以控制插入图表的大小,为了显示效果,需先设置好单元格大小,使其同大小
  3. bar1.Format.Fill对柱状图填充使用Fill
  4. bar1.Format.Line对柱状图轮廓使用Line
  5. ch1.Chart.Axes(xlValue)对坐标轴进行设置
  6. ch1.Chart.ChartGroups(1).GapWidth = 82对其分类间距进行设置,见下图

分类间距
这里写图片描述


以上为本次的学习内容,下回见

本文为原创作品,如若转载请标明出处,如发现有错误,欢迎留言指出


更多原创请关注微信公众号

扫描二维码,关注公众号
让重复工作一键化,让时间更有意义
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值