设置图表系列颜色以匹配类别单元格颜色VBA

我需要VBAmacros,这将匹配我的类别背景颜色与折线图系列颜色。 现在我不使用最好的方式,因为我正在应用下面的代码
代码是如何工作的

它将图表系列颜色设置为与源单元格颜色相同。 (例如在图片上)

但是我想要这个macros从类别的单元格(2009,2010,2011代表),而不是源单元格的颜色。

我找不到简单而直接的方法。 我为源单元格macros设置背景颜色来匹配类别的颜色,然后我把白色的颜色与条件格式的源单元格的顶部。 所以只有类别是多彩的,源单元格是白色的。 这就是最后的样子

想知道是否有更好的方法做到这一点。 (图片上的最终结果,匹配系列颜色的类别名称)

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 

假设我完全明白你在问什么,那么你离得很近。 我认为你的代码中的问题是你如何分割系列公式来获得标签的颜色。

我把这个图表转成了这样的颜色:

在这里输入图像说明

进入下面的图表与此代码:

 Sub SetColors() Dim oChart As ChartObject Dim MySeries As Series For Each oChart In ActiveSheet.ChartObjects For Each MySeries In oChart.Chart.SeriesCollection Dim sFormula As String sFormula = Split(MySeries.Formula, ",")(0) 'this returns the =SERIES(Sheet!RC part of the formula, the first argument is the series label sFormula = Split(sFormula, "(")(1) 'this removes the =SERIES( leaving only the column label range (Sheet!RC) Dim lSourceColor As Long lSourceColor = Range(sFormula).Interior.Color With MySeries .Interior.Color = lSourceColor .Border.Color = lSourceColor '.MarkerBackgroundColorIndex = lSourceColor '.MarkerForegroundColorIndex = lSourceColor .MarkerBackgroundColor = lSourceColor .MarkerForegroundColor = lSourceColor With .Format.Line .ForeColor.RGB = lSourceColor .BackColor.RGB = lSourceColor End With .Format.Fill.ForeColor.RGB = lSourceColor End With Next Next End Sub 

在这里输入图像说明