Changing Bar colors using VBA based on category label

前端 未结 2 1819
夕颜
夕颜 2020-12-22 10:28

I have a VBA code in excel to change colors of bar graph but its not working for category series.

ActiveChart.SeriesCollection(1).Interior.Color = RGB(0, 15         


        
相关标签:
2条回答
  • 2020-12-22 11:31

    Jesse's answer is often the cleanest way to do it.

    However, it is not accurate that "to have different colored bars they must be on different series" (my emphasis). You can mix and match colors within one series. For example, this makes the second bar of the first series red:

    ActiveChart.SeriesCollection(1).Points(2).Interior.Color = RGB(255, 0, 0)
    

    You can use this to do all kinds of neat tricks, such as highlighting bars that exceed some threshold, are associated with leap years, or whatever. You could certainly choose to highlight your average1 and average2 values this way.


    If you want to change the color for a point that has a given characteristic, then you have to loop through all points until you find a point that has that characteristic. For example, if you want to color in red the point whose category (XValue) is "avg" then you could do this:

    Dim c As Chart
    Dim s As Series
    Dim iPoint As Long
    Dim nPoint As Long
    
    Set c = ActiveChart
    Set s = c.SeriesCollection(1)
    
    nPoint = s.Points.Count
    For iPoint = 1 To nPoint
        If s.XValues(iPoint) = "avg" Then
            s.Points(iPoint).Interior.Color = RGB(255, 0, 0)
        End If
    Next iPoint
    
    0 讨论(0)
  • 2020-12-22 11:34

    Your problem isn't with the VBA, to have different colored bars they must be on different series.

    Leave a gap in the base colored series and add the values you want colored on a second series and color that. Your data would look something like this:

    Series | Month 1 | Month 2 | Month 3 | Month 4 | Month 5 | Month 6 | Month 7
      1         10        12       15                   14                  10
      2                                       17
      3                                                           18
    
    0 讨论(0)
提交回复
热议问题