此 VBA 片段将绘制条形图并将列中的最终值用作条形的颜色索引。
要使用它,只需选择两列数据(包括标题和最后一行),然后点击F5
以下代码:
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