将RGB转换为Long的RGB()值

时间:2015-07-28 18:50:18

标签: vba excel-vba rgb excel

我正在编写一个宏来识别单元格的RGB值,然后将其作为参数传递给条件格式。唯一的问题是使用以下:

RGBcolor1 = "RGB(" & CInt("&H" & Right(HEXcolor1, 2)) & _
", " & CInt("&H" & Mid(HEXcolor1, 3, 2)) & _
", " & CInt("&H" & Left(HEXcolor1, 2)) & ")"

其中:

HEXcolor1 = Right("000000" & Hex(Sheet1.[LowColour].Interior.Color), 6)

RGB值是一个字符串,而为了将其作为.Color传递,我需要它是一个长(Color = rgb(255, 0, 0))

我知道存在使用Debug窗口来检索?rgb(255,0,0)的解决方案,但是,我希望自动化该过程。我尝试了Clng()以及.Evaluate(),但他们没有用。

任何帮助都非常感谢!

2 个答案:

答案 0 :(得分:1)

You'll have to parse the string. You could use a regex or just make some simple replacements to isolate just the digits. For example:

strColor = "RGB(123, 0, 234)"
strColor = Replace(strColor, "RGB", "")
strColor = Replace(strColor,   "(", "")
strColor = Replace(strColor,   ")", "")
strColor = Replace(strColor,   " ", "")

Dim a As Variant, c As Long
a = Split(strColor, ",")
c = a(0) * &H10000 + a(1) * &H100 + a(2)

Range("A1").Interior.Color = c

Or, with a regex (you'll have to add a reference to the Microsoft VBScript Regular Expressions 5.5 library):

With New RegExp
    .Global = True
    .Pattern = "[^\d,]"    ' Remove anything that's not a digit or comma
    Dim a As Variant, c As Long
    a = Split(.Replace(strColor, ""), ",")
    c = a(0) * &H10000 + a(1) * &H100 + a(2)
End If

Range("A1").Interior.Color = c

Edit:

Here's a quick but hacky way, using Eval() from the Microsoft Script Control:

With CreateObject("MSScriptControl.ScriptControl")
    .Language = "VBScript"
    Range("A1").Interior.Color = .Eval(strColor)
End With

答案 1 :(得分:0)

您可以使用val()函数

进行转换
Dim l as long
dim str as string

str = "111111"
l = val(str)

CLng(Val(str))