简体   繁体   中英

Map Excel worksheet column to Bar Graph color

If I have a chart like:

        x   y
        1   3
        2   8
        3   9
        4   0
color   3   1

is it possible to create a bar graph in Excel (2007) where there are bars for X and Y and the color index of each bar could be associated to the last row (labeled color) of the table?

This VBA snippet will plot a bar chart and use the final values in the columns as a colorindex for the bars.

To use this, simply select the two columns of data (including headers and final row) and then hit F5 on the following code:

Sub BarChartWithColors()
    Dim selectedRng As Range, chartRng As Range, colorRng As Range

    Set selectedRng = Selection
    Set chartRng = Range(Selection.Cells(1, 1), Selection.Cells(selectedRng.Rows.Count - 1, 2))
    Set colorRng = Range(Selection.Cells(selectedRng.Rows.Count, 1), Selection.Cells(selectedRng.Rows.Count, 2))

    Charts.Add
    ActiveChart.ChartType = xlBarClustered
    ActiveChart.SetSourceData Source:=chartRng, PlotBy:=xlColumns
    ActiveChart.Location Where:=xlLocationAsObject, Name:="Sheet1" //Change sheet destination as appropriate
    ActiveChart.SeriesCollection(1).Interior.ColorIndex = colorRng.Cells(1, 1)
    ActiveChart.SeriesCollection(2).Interior.ColorIndex = colorRng.Cells(1, 2)
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM