【问题标题】:How to change background color and set bar colors based on conditional formatting in VBA?如何根据 VBA 中的条件格式更改背景颜色和设置条形颜色?
【发布时间】:2021-04-28 17:38:45
【问题描述】:

这是我需要从 VBA 为我的个人数据点制作的图表格式:

Chart Style Needed Example

我不知道如何将背景颜色更改为蓝色,将轴标题颜色和线条颜色更改为白色,我需要根据上图所示的值设置条形颜色。因此,如果条形的值为 2.9,则为红色,如果为 3.5,则为金色,如果大于 4,则为绿色。

这是我目前的代码:

Sub CreateBarChart()
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.SetSourceData Source:=Range("$B$4:$F$5")
    ActiveChart.ChartType = xlBarClustered
    ActiveChart.Axes(xlValue).HasTitle = False
    ActiveChart.Axes(xlCategory).HasTitle = False
    ActiveChart.HasLegend = False
    ActiveChart.ChartTitle.Delete
    ActiveChart.Axes(xlValue).TickLabels.NumberFormat = "0.0"
                
End Sub

【问题讨论】:

  • 您可以在进行这些更改时使用宏记录器来捕获事件,然后尝试使用生成的代码作为起点。

标签: excel vba


【解决方案1】:

定义活动图表:

Dim c As Chart
Set c = ActiveChart

要为背景着色,请使用:c.ChartArea.Interior.Color = vbBlue

要根据值对点进行着色,您可以将系列定义为数组,然后计算数组中的每个值:

seriesarray = c.SeriesCollection(1).Values      'define array
For i = 1 To UBound(seriesarray)      'for each value in array
   If seriesarray(i) < 3 Then      'if below 3, red
    c.SeriesCollection(1).Points(i).Interior.Color = vbRed
    ElseIf seriesarray(i) >= 3 And seriesarray(i) < 4 Then     'if between 3-4, yellow
    c.SeriesCollection(1).Points(i).Interior.Color = vbYellow
    ElseIf seriesarray(i) >= 4 Then      'if 4 or above, green
    c.SeriesCollection(1).Points(i).Interior.Color = vbGreen
   End If
Next i

reference for changing bar colors

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-21
    • 2011-04-23
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    相关资源
    最近更新 更多