问题
I have a VBA code to automatically change the color in a chart, which I found from this site: http://datapigtechnologies.com/blog/index.php/automatically-set-chart-series-colors-to-match-source-cell-colors/
The code is posted below. My problem is that I need this code to apply to the chart's horizontal categories instead of the series because I am using a horizontal bar chart and the data has to be arranged in this way. How can I change the VBA to apply the automatic color change to the categories?
Sub CellColorsToChart()
Dim oChart As ChartObject
Dim MySeries As Series
Dim FormulaSplit As Variant
Dim SourceRange As Range
Dim SourceRangeColor As Long
'Loop through all charts in the active sheet
For Each oChart In ActiveSheet.ChartObjects
'Loop through all series in the target chart
For Each MySeries In oChart.Chart.SeriesCollection
'Get Source Data Range for the target series
FormulaSplit = Split(MySeries.Formula, ",")
'Capture the first cell in the source range then trap the color
Set SourceRange = Range(FormulaSplit(2)).Item(1)
SourceRangeColor = SourceRange.Interior.Color
On Error Resume Next
'Coloring for Excel 2003
MySeries.Interior.Color = SourceRangeColor
MySeries.Border.Color = SourceRangeColor
MySeries.MarkerBackgroundColorIndex = SourceRangeColor
MySeries.MarkerForegroundColorIndex = SourceRangeColor
'Coloring for Excel 2007 and 2010
MySeries.MarkerBackgroundColor = SourceRangeColor
MySeries.MarkerForegroundColor = SourceRangeColor
MySeries.Format.Line.ForeColor.RGB = SourceRangeColor
MySeries.Format.Line.BackColor.RGB = SourceRangeColor
MySeries.Format.Fill.ForeColor.RGB = SourceRangeColor
Next MySeries
Next oChart
End Sub
回答1:
The following code does something along the lines you are asking. It iterates through the points and colours them to the background colour of the cell and iterates through multiple series if they exist.
Sub CellColorsToChart()
Dim oChart As ChartObject
Dim MySeries As Series
Dim FormulaSplit As Variant
Dim SourceRangeColor As Long
Dim seriesArray() As Variant
Dim pointIterator As Integer
For Each oChart In ActiveSheet.ChartObjects
For Each MySeries In oChart.Chart.SeriesCollection
seriesArray = MySeries.Values
For pointIterator = 1 To UBound(seriesArray)
FormulaSplit = Split(MySeries.Formula, ",")
SourceRangeColor = Range(FormulaSplit(2)).Item(pointIterator).Interior.Color
MySeries.Points(pointIterator).Interior.Color = SourceRangeColor
Next pointIterator
Next MySeries
Next oChart
End Sub
来源:https://stackoverflow.com/questions/22924456/automatically-set-chart-series-colors-to-match-source-cell-colors-by-category-no