VBA Excel - 设置行背景取决于单元格值
VBA Excel - Set row background depends on cell value
我在 Excel 中有这样的行:
Subject VariableName VariableValue
Color vColor_Chart1 RGB(217,217,217)
Color vColor_Chart2 RGB(210,110,42)
我想创建宏来根据 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
而且我不知道如何 'run' 来自 cell.value 的 RGB 函数。
来自 rngRow.Interior.Color = rgbCell
行的错误:
Run-time error '13':
Type mismatch
RGB Function (Visual Basic) 是一个 VBA 函数,它从三个整数构建颜色常量。您不能通过传入 看起来 像完整函数调用的文本字符串来使用它。
如果您绝对确定将公式作为单元格中的文本,那么从文本字符串中计算公式的一些操作就足够了。
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
您必须将 rngRow.Interior.Color
设置为实际的颜色对象,但您当前将其设置为字符串。如果您在代码中更改此行:
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
然后将从字符串中的数字构建颜色对象。
我在 Excel 中有这样的行:
Subject VariableName VariableValue
Color vColor_Chart1 RGB(217,217,217)
Color vColor_Chart2 RGB(210,110,42)
我想创建宏来根据 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
而且我不知道如何 'run' 来自 cell.value 的 RGB 函数。
来自 rngRow.Interior.Color = rgbCell
行的错误:
Run-time error '13':
Type mismatch
RGB Function (Visual Basic) 是一个 VBA 函数,它从三个整数构建颜色常量。您不能通过传入 看起来 像完整函数调用的文本字符串来使用它。
如果您绝对确定将公式作为单元格中的文本,那么从文本字符串中计算公式的一些操作就足够了。
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
您必须将 rngRow.Interior.Color
设置为实际的颜色对象,但您当前将其设置为字符串。如果您在代码中更改此行:
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
然后将从字符串中的数字构建颜色对象。