vba - Excel:使用 rgb 设置单元格的背景颜色和文本颜色

标签 vba excel rgb background-color textcolor

我正在编写一个根据用户请求更改字体和背景颜色的程序。在收到 backgroundColorDatatextColorData 之后 由于用户的要求,我确实喜欢改变颜色,但我觉得有比我选择做的更好的方法(我的代码可能会重复自己) 另一个我没有找到答案的问题是如何使 textColor/backgroundColor 更“红”或更“蓝”

  Select Case backgroundColorData
        Case Is = "Black"
            Selection.Interior.Color = RGB(0, 0, 0)
        Case Is = "Red"
             Selection.Interior.Color = RGB(255, 0, 0)
        Case Is = "Blue"
             Selection.Interior.Color = RGB(0, 0, 255)
        Case Is = "White"
             Selection.Interior.Color = RGB(255, 255, 255)
  End Select


    Select Case textColorData
        Case Is = "Black"
            Selection.Font.Color = RGB(0, 0, 0)
        Case Is = "Red"
             Selection.Font.Color = RGB(255, 0, 0)
        Case Is = "Blue"
             Selection.Font.Color = RGB(0, 0, 255)
        Case Is = "White"
             Selection.Font.Color = RGB(255, 255, 255)
     End Select  

如有任何帮助,我们将不胜感激。

最佳答案

Sub tester()

    Dim backgroundColorData As String, textColorData As String

    backgroundColorData = "Blue"
    textColorData = "White"

    With Selection
        .Interior.Color = NameToRgb(backgroundColorData)
        .Font.Color = NameToRgb(textColorData)
    End With

End Sub

'map a color name to an rgb value
Function NameToRgb(sName As String) As Long
    Dim arrNames, arrRGB, v
    arrNames = Array("black", "red", "blue", "white")
    arrRGB = Array(RGB(0, 0, 0), RGB(255, 0, 0), _
                   RGB(0, 0, 255), RGB(255, 255, 255))

    v = Application.Match(LCase(sName), arrNames, 0)
    If Not IsError(v) Then
        NameToRgb = arrRGB(v - 1)
    Else
        NameToRgb = vbBlack 'default...
    End If
End Function

如果您想为“更红”的东西找到确切的颜色值,请将单元格中的背景设置为您想要的颜色,选择该单元格,然后在 VB 编辑器的即时 Pane 中键入:

? Selection.Interior.Color 

复制数字并使用它代替您的 RGB() 值

编辑:好的,现在我明白你所说的让细胞更红的意思了......

Sub MoreRed(c As Range)
    Dim R As Long, G As Long, B As Long, clr As Long

    clr = c.Interior.Color
    B = clr \ 65536
    G = (clr - B * 65536) \ 256
    R = clr - B * 65536 - G * 256
    'Debug.Print R, G, B
    R = Application.Min(R + 20, 255) 'more red...
    c.Interior.Color = RGB(R, G, B)
End Sub

关于vba - Excel:使用 rgb 设置单元格的背景颜色和文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40566478/

相关文章:

opencv - 颜色检测opencv

C++ 从 hBitmap 获取 RGB

database - 重复条目警告消息框

vba - 将数字四舍五入到最接近的 5 或 10 或 X

java - Apache POI Excel 行和列索引

excel - If Not (range) or (range) = Nothing Then

c# - AddPicture 有替代品吗? (C#,Epplus)

r - 在R中,是否可以在绘图中叠加2种颜色以形成第3种颜色(例如,使用加色或减色混合)

vba - 使用 VBA 将数据从 Microsoft Excel 获取到 Powerpoint 图表中

excel - 有没有办法在vba中编辑公式