Question

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?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top