gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:31:26 31 4
gpt4 key购买 nike

我正在编写一个根据用户请求更改字体和背景颜色的程序。在收到 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com