【问题标题】:VBA Excel - Set row background depends on cell valueVBA Excel - 设置行背景取决于单元格值
【发布时间】:2015-03-17 18:49:58
【问题描述】:

我在 Excel 中有这样的行:

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

我想创建宏来改变行背景取决于变量值列中的单元格值。

我现在有这样的代码:

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”:
类型不匹配

【问题讨论】:

    标签: vba excel rgb


    【解决方案1】:

    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
    

    【讨论】:

      【解决方案2】:

      您必须将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
      

      然后这将从字符串中的数字构建颜色对象。

      【讨论】:

      • 这个版本解决我的问题很简单!我以为我必须像@Jeeped 那样做某事,但我没有。 :) 谢谢!
      • 你甚至可以不用'Val',除了最后一个: sp = Split(Mid(c00, 5), ",") y = RGB(sp(0), sp(1 ), Val(sp(2)))
      • @snb 是正确的。我不需要Val(即使是第三个参数——不知道你为什么认为我仍然需要它作为最后一个参数)。以上更新!顺便说一句,@Jeeped 的答案和我的几乎一模一样,虽然我猜单曲 Split 更简洁。
      猜你喜欢
      • 2012-09-07
      • 2021-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      • 2011-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多