You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MS Access柱状图中指定数据系列柱体颜色?

Access Modern Chart 动态设置柱体颜色解决方案

你遇到的运行时错误438是因为Modern Chart对象的ChartSeries并非直接可访问的顶层属性,正确的做法是通过SeriesCollection集合或者底层Excel图表对象来设置柱体颜色,以下是两种可行方案:

方案一:使用Modern Chart原生的SeriesCollection属性

Modern Chart的数据系列存储在SeriesCollection集合中,直接访问对应索引的系列即可设置填充颜色,注意先执行Requery刷新数据,再设置格式,否则可能找不到系列。修改后的代码如下:

Private Sub cbo_ShipType_Change()
    Dim strSQL As String, cht As Chart, lngBlack As Long, lngBlue As Long
    
    lngBlack = RGB(0, 0, 0)
    lngBlue = RGB(0, 0, 255) ' RGB值范围为0-255,原256会自动转为0,修正为255
    
    Set cht = Me.cht_ShipType
    strSQL = "SELECT tbl_ChartData.[YR], " & cbo_ShipType & " FROM tbl_ChartData"
    cht.RowSource = strSQL
    cht.Requery ' 先刷新数据,确保系列已加载
    
    With cht
        .ChartTitle = cbo_ShipType & " Fleet Size"
        .PrimaryValuesAxisFontSize = 14
        .PrimaryValuesAxisFontColor = lngBlack
        .CategoryAxisFontSize = 12
        .CategoryAxisFontColor = lngBlack
        
        ' 检查系列是否存在,避免索引越界错误
        If .SeriesCollection.Count > 0 Then
            .SeriesCollection(1).Fill.Color = lngBlue
        End If
    End With
End Sub

方案二:通过AutomationObject调用Excel图表模型

Access的Modern Chart本质是嵌入的Excel图表,通过AutomationObject可以直接操作底层Excel图表对象,支持更丰富的格式设置,兼容性更强:

Private Sub cbo_ShipType_Change()
    Dim strSQL As String, cht As Chart, lngBlack As Long, lngBlue As Long
    Dim xlChart As Object ' 声明为通用对象,避免引用Excel库
    
    lngBlack = RGB(0, 0, 0)
    lngBlue = RGB(0, 0, 255)
    
    Set cht = Me.cht_ShipType
    strSQL = "SELECT tbl_ChartData.[YR], " & cbo_ShipType & " FROM tbl_ChartData"
    cht.RowSource = strSQL
    cht.Requery
    
    ' 获取底层Excel Chart对象
    Set xlChart = cht.AutomationObject
    With xlChart
        .ChartTitle.Text = cbo_ShipType & " Fleet Size"
        ' 设置数值轴字体
        .Axes(xlValue).TickLabels.Font.Size = 14
        .Axes(xlValue).TickLabels.Font.Color = lngBlack
        ' 设置分类轴字体
        .Axes(xlCategory).TickLabels.Font.Size = 12
        .Axes(xlCategory).TickLabels.Font.Color = lngBlack
        
        ' 设置柱体填充色
        If .SeriesCollection.Count > 0 Then
            .SeriesCollection(1).Interior.Color = lngBlue
        End If
    End With
    
    Set xlChart = Nothing ' 释放对象
End Sub

关键注意事项:

  • RGB值范围是0-255,原代码中RGB(0,0,256)会被自动转换为RGB(0,0,0),导致颜色不符合预期,需修正为255。
  • 每次切换系列后必须先执行Requery,确保图表数据刷新完成再设置格式,否则可能出现系列未加载的情况。
  • 添加SeriesCollection.Count > 0的判断,避免因数据为空导致的索引越界错误。

内容的提问来源于stack exchange,提问作者Kevin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 23:36:01