Excel 2007 Change colour of bars in a single series, based on another field

和自甴很熟 提交于 2019-12-13 02:48:00

问题


I have a pivot table with data like this:

Chain     Store               Units
Bob's     BB Los Angeles        10
Bob's     BB San Diego          12
Tom's     TM Los Angeles        12
Tom's     TM San Francisco      18
Kate's    K Monterey            11

Currently I have a bar chart just showing all stores and units in descending order, so TM San Francisco is first, then TM Los Angeles and BB San Diego, then K Monterey etc. This is how I want to see the data.

But I also want to colour code the chains, so Bob's stores have a red bar, Tom's have blue, and Kate's are green.

Is it possible to do this? I've tried various ways of setting out the pivot table but it ends up looking a mess and I can't find a way of basing the each bar's colour on the 'chain' field.

=

Am testing the macro solution, but if anyone has a non-macro solution then do please still answer. :)


回答1:


If you're looking for a macro/VBA-based solution, this is pretty easy to manipulate the chart's data point formatting. Assuming that the series XValues = Chain, you could do this:

Sub SetColors()
Dim cht As Chart
Dim srs As Series
Dim xVals As Variant
Dim p As Long

Set cht = ActiveSheet.ChartObjects(1).Chart '<-- Modify as needed'
Set srs = cht.SeriesCollection(1) '<-- Modify as needed'

xVals = srs.XValues  '<-- modify as needed, if your Chain is not part of series data you will need to build this array another way'

For p = 1 To UBound(xVals)
    Select Case xVals(p)
        Case "Bob's"
            srs.Points(p).Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
        Case "Tom's"
            srs.Points(p).Format.Fill.ForeColor.RGB = RGB(0, 255, 0)
        Case "Kate's"
            srs.Points(p).Format.Fill.ForeColor.RGB = RGB(0, 0, 255)
    End Select
Next
End Sub

If the Chain is NOT part of the series data, you'd have to change the way that xVals is set, but the general principle should still apply: Iterate over the points in the series, check against a reference list, and apply a specific color based on the reference item.



来源:https://stackoverflow.com/questions/16014342/excel-2007-change-colour-of-bars-in-a-single-series-based-on-another-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!