根据单元格的背景颜色亮度自动设置字体颜色

-1 excel formatting vba colors

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

Pᴇʜ*_*Pᴇʜ 6

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

\n

然后可以用公式计算亮度

\n
sqrt(0.299 * R\xc2\xb2 + 0.587 * G\xc2\xb2 + 0.114 * B\xc2\xb2)\n
Run Code Online (Sandbox Code Playgroud)\n

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

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

在此输入图像描述\n图片 1:不同的背景颜色。

\n

在此输入图像描述\n图片 2:不同的背景颜色,根据背景的亮度,字体颜色为白色或黑色。

\n