我编写了一个程序,可以根据用户请求更改字体和背景颜色。收到 backgroundColorData 和 textColorData 后 我确实喜欢根据用户要求改变颜色,但我觉得有更好的方法让它成为我选择做的(我的代码可能会重复) 其他问题我没有找到答案是如何使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
任何帮助都将不胜感激。
答案 0 :(得分:2)
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编辑器中立即显示窗格:
? 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
答案 1 :(得分:1)
欢迎使用堆栈溢出。
你可以用这样的单一功能来实现 -
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)