Excel: 设置单元格背景颜色和文本颜色为 rgb

Excel: Set background color of cell and text color with rgb

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

  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  

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

欢迎来到堆栈溢出。

你可以用这样一个函数来完成-

Function setColor(SelectionData As String) 

 Select Case SelectionData As String
      Dim returnValue As String  
        Case Is = "Black"
            returnValue  = RGB(0, 0, 0)
        Case Is = "Red"
             returnValue  = RGB(255, 0, 0)
        Case Is = "Blue"
             returnValue  = RGB(0, 0, 255)
        Case Is = "White"
             returnValue  = RGB(255, 255, 255)
     End Select  
return returnValue  
End Function

然后像这样调用你的函数-

setColor(textColorData)
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

如果您想为某些东西找到确切的颜色值 "more red",请将单元格中的背景设置为您想要的颜色,select 单元格,然后在 VB编辑器直接窗格类型:

? 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