如何根据 VBA 中的条件格式更改背景颜色和设置条形颜色?

时间:2021-04-28 17:38:45

标签: excel vba

这是我需要从 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

1 个答案:

答案 0 :(得分:0)

定义活动图表:

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

相关问题