VBA Excel – 设置行背景取决于单元格的值

我在Excel中有这样的行:

Subject VariableName VariableValue Color vColor_Chart1 RGB(217,217,217) Color vColor_Chart2 RGB(210,110,42) 

我想创buildmacros来改变行背景依赖于VariableValue列中的单元格值。

我现在有这样的代码:

 Sub SetBackground() Dim rngRange As Range Dim rngRow As Range Dim rgbCell As Range Set rngRange = Range("A2:K13") For Each rngRow In rngRange.Rows Set rgbCell = Range("E" & rngRow.Row) ' E it is column of VariableValue in my sheet rngRow.Interior.Color = rgbCell.Value 'here it doesn't works Next End Sub 

我不知道如何从cell.value'运行'RGB函数。

来自rngRow.Interior.Color = rgbCell行的错误:

运行时错误“13”:
types不匹配

您必须将rngRow.Interior.Color设置为实际颜色对象,但是您当前将其设置为string。 如果您在代码中更改此行:

 rngRow.Interior.Color = rgbCell.Value 'here it doesn't works 

对此:

 If Left(rgbCell.Value, 4) = "RGB(" Then rgbValues = Split(Mid(rgbCell.Value, 5, Len(rgbCell.Value) - 5), ",") rngRow.Interior.Color = RGB(rgbValues(0), rgbValues(1), rgbValues(2)) End If 

然后,将从string中的数字构build颜色对象。

RGB函数(Visual Basic)是一个VBA函数,它可以从三个整数中构build颜色常量。 你不能通过传入一个看起来像完全形成的函数调用的文本string来使用它。

如果你完全确定在单元格中有公式作为文本,那么从文本string中评估公式的操作应该足够了。

 Dim sRGB As String, r As Integer, g As Integer, b As Integer sRGB = rgbCell.Value 'example: "RGB(210,110,42)" r = Int(Split(Split(sRGB, ",")(0), "(")(1)) g = Int(Split(sRGB, ",")(1)) b = Int(Split(Split(sRGB, ",")(2), ")")(0)) 'Debug.Print RGB(r, g, b) rngRow.Interior.Color = RGB(r, g, b) 'here it works