根据颜色常数的单元格值更改内部颜色

时间:2017-07-08 16:06:19

标签: excel-vba vba excel

我有一个带有8种颜色常数的Excel范围。我只是想根据单元格值简单地更改相邻列中单元格的内部颜色。不幸的是,我得到的类型不匹配是因为它将值视为字符串,但我不知道如何将其转换为常量。

例如,要将内部颜色更改为蓝色,这是有效的 rng.interior.color = vbblue

但不是这个 rng.interior.color = rng.value'因为它是一个字符串" vbblue"

如何将rng.value从字符串转换为颜色常量,以便E列中的范围根据D列中的值获得背景颜色?

range

Dim colorRange As Range
Dim rng As Range
Set colorRange = Range("D1", Range("D1").End(xlDown).Address)

For Each rng In colorRange
  rng.Offset(, 1).Interior.Color = rng.Value
Next rng

2 个答案:

答案 0 :(得分:2)

没有“内置”方式将Constant的名称转换为其值。您需要自己进行映射。最好是使用字典:

Function TextToColor(s As String) As Long
  Static dict As Dictionary
  If dict Is Nothing Then
    Set dict = CreateObject("Scripting.Dictionary")
    dict("vbBlack") = vbBlack
    dict("vbWhite") = vbWhite
    dict("vbRed") = vbRed
    dict("vbGreen") = vbGreen
    dict("vbBlue") = vbBlue
    dict("vbYellow") = vbYellow
    dict("vbMagenta") = vbMagenta
    dict("vbCyan") = vbCyan
    ' dict("etc...") = etc...
  End If
  TextToColor = dict(s)
End Function
Sub ExampleUse()
  Dim colorRange As Range: Set colorRange = Range("D1", Range("D1").End(xlDown).Address)
  Dim rng As Range
  For Each rng In colorRange
    rng.Offset(, 1).Interior.Color = TextToColor(rng.value)
  Next rng
End Sub

答案 1 :(得分:0)

您可以直接使用ColorIndex进行操作。因此,如果单元格显示5或相关的颜色索引号,则无需更改此行以外的代码:

rng.Offset(,1).Interior.Color 索引 = rng.Value