【问题标题】:Automate font color depending on cell's background color brightness [closed]根据单元格的背景颜色亮度自动化字体颜色[关闭]
【发布时间】:2021-02-21 11:39:03
【问题描述】:

如何在 Excel 中创建一个宏,根据单元格的背景颜色亮度(可以是 Excel 能够产生的任何颜色)将所有字体颜色更改为黑色或白色,目的是最大化字体之间的对比度和单元格的背景颜色?

【问题讨论】:

  • “有没有可能”的问题在这里往往做得不太好。您可能想查看How to Ask 并选择tour。 SO 并不是一个真正的代码编写站点,而是针对现有代码的问题。这个问题太笼统了。
  • 即使根据How to Ask,这不是一个很好的问题,我认为回答这个问题可能对未来的读者有所帮助。

标签: excel vba colors formatting


【解决方案1】:

这可以通过使用颜色的 RGB 值计算 HSP 模型来实现。因此,Interior.Color 值需要先转换为 Hex 才能检索十进制 RGB 值。

那么亮度可以用公式计算

sqrt(0.299 * R² + 0.587 * G² + 0.114 * B²)

根据http://alienryderflex.com/hsp.html,您可以定义一个您认为是亮色或暗色的阈值,例如使用If hsp > 127.5 Then之类的东西。

Option Explicit

Public Sub test()
    BlackWhiteFontColor Range("A1:A10")
End Sub

Public Sub BlackWhiteFontColor(ByRef FormatRange As Range)
    Dim Cell As Range
    For Each Cell In FormatRange.Cells
        Dim Color As Long
        Color = Cell.Interior.Color
        
        'covert color into hex color
        Dim RGBHex As String
        RGBHex = Right$("000000" & Hex(Color), 6)
        
        'extract rgb values
        Dim Blue As Long, Green As Long, Red As Long
        Blue = CLng("&H" & Mid$(RGBHex, 1, 2))
        Green = CLng("&H" & Mid$(RGBHex, 3, 2))
        Red = CLng("&H" & Mid$(RGBHex, 5, 2))
        
        'calculate hsp according to http://alienryderflex.com/hsp.html
        Dim hsp As Double
        hsp = Sqr(0.299 * (Red ^ 2) + 0.587 * (Green ^ 2) + 0.114 * (Blue ^ 2))
        
        If hsp > 127.5 Then
            'background color is light
            Cell.Font.Color = vbBlack
        Else
            'background color is dark
            Cell.Font.Color = vbWhite
        End If
    Next Cell
End Sub

图 1:不同的背景颜色。

图 2:不同的背景颜色,有白色或黑色字体颜色,具体取决于背景的亮度。

【讨论】:

  • 爱它,非常有用的颜色模型:+)
【解决方案2】:

在 Pᴇʜ 的出色答案的基础上,除了计算的 HSP 值之外,您还可以利用条件格式为图层着色的文本

您可以将条件格式公式=IsDark(A1) {font color = white} 与以下函数结合使用以实现类似的着色:

Public Function IsDark(ByRef Cell As Range) As Boolean
    If Cell.Cells.Count > 1 Then Exit Function
    Dim Blue As Long, Green As Long, Red As Long, PerceivedColor As Double
    
    Red = Cell.Interior.Color Mod 256
    Green = Cell.Interior.Color \ 256 Mod 256
    Blue = Cell.Interior.Color \ 65536 Mod 256
    PerceivedColor = 0.299 * (Red ^ 2) + 0.587 * (Green ^ 2) + 0.114 * (Blue ^ 2)
    IsDark = IIf(Sqr(PerceivedColor) > 127.5, False, True)
End Function

【讨论】:

  • 嗯,使用模数比像我那样通过十六进制要容易得多。 +1
猜你喜欢
  • 2016-04-03
  • 2013-06-03
  • 1970-01-01
  • 2020-12-13
  • 1970-01-01
  • 2011-04-03
  • 2014-11-20
  • 2016-02-08
相关资源
最近更新 更多