如何使用单元格内的hex颜色值突出显示单元格?

我有一个符号和匹配hex颜色的电子表格。 我想用单元格内的hex颜色填充单元格本身(或旁边的单元格)。 我已经读了一些关于“条件格式化”的内容,我认为这是做到这一点的方法。

我怎么能达到我想要的结果?

对于所有颜色都不能使用条件格式来实现。

假设:Row1包含数据标签,数据集没有间隙,hex颜色用于填充而不是字体,您已经将HEX颜色值(数字,不是公式)parsing为列C:E(R,G,B)而且你不需要经常这样做,那么ColourCellsmacros可能适合:

 Sub ColourCells() Dim HowMany As Integer On Error Resume Next Application.DisplayAlerts = False HowMany = Application.InputBox _ (Prompt:="Enter last row number.", Title:="To apply to how many rows?", Type:=1) On Error GoTo 0 Application.DisplayAlerts = True If HowMany = 0 Then Exit Sub Else Dim i As Integer For i = 2 To HowMany Cells(i, 3).Interior.Color = RGB(Cells(i, 3), Cells(i, 4), Cells(i, 5)) Next i End If End Sub 

并在提示时input你想要的值。

示例输出和公式等:

SO11466034

Excel的RGB()函数实际上创build了一个BGR值(我不认为有人可能知道为什么要这样说),所以Excel以相反的顺序显示半字节。 对于代码列3,4,5是逻辑的,但BGR而不是传统的RGB在图像中,我认为可能看起来很奇怪。 对于图像中的F值,C3值(“RGB”三的左手栏)是通过将RIGHT()应用于hex颜色而得出的。

对乔·帕尔帖的回答进行小修改。 他的functionALMOST工作,但它呈现的颜色是不正确的,因为Excel将显示为BGR而不是RGB。 这里是修正的函数,它将Hex对的值交换为“正确的”顺序:

 Sub ColorCellsByHex() Dim rSelection As Range, rCell As Range, tHex As String If TypeName(Selection) = "Range" Then Set rSelection = Selection For Each rCell In rSelection tHex = Mid(rCell.Text, 6, 2) & Mid(rCell.Text, 4, 2) & Mid(rCell.Text, 2, 2) rCell.Interior.Color = WorksheetFunction.Hex2Dec(tHex) Next End If End Sub 

更简单:

 ActiveCell.Interior.Color = WorksheetFunction.Hex2Dec(Mid$(ActiveCell.Text, 2)) 

中间去掉前面的“#”,Hex2Dec将hex数转换成VBA可以使用的十进制值。

所以select要处理的范围,并运行这个:

 Sub ColorCellsByHexInCells() Dim rSelection As Range, rCell As Range If TypeName(Selection) = "Range" Then Set rSelection = Selection For Each rCell In rSelection rCell.Interior.Color = WorksheetFunction.Hex2Dec(Mid$(rCell.Text, 2)) Next End If End Sub 

为此,可以使用Hex2Dec函数创build一个用户窗体。

 Function Hex2Dec(n1 As String) As Long Dim nl1 As Long Dim nGVal As Long Dim nSteper As Long Dim nCount As Long Dim x As Long Dim nVal As Long Dim Stepit As Long Dim hVal As String nl1 = Len(n1) nGVal = 0 nSteper = 16 nCount = 1 For x = nl1 To 1 Step -1 hVal = UCase(Mid$(n1, x, 1)) Select Case hVal Case "A" nVal = 10 Case "B" nVal = 11 Case "C" nVal = 12 Case "D" nVal = 13 Case "E" nVal = 14 Case "F" nVal = 15 Case Else nVal = Val(hVal) End Select Stepit = (nSteper ^ (nCount - 1)) nGVal = nGVal + nVal * Stepit nCount = nCount + 1 Next x Hex2Dec = nGVal End Function ... UserForm1.TextBox1 = "RGB(" & Hex2Dec(UserForm1.txtHex1.Value) & "," & _ Hex2Dec(UserForm1.txtHex2.Value) & "," & Hex2Dec(UserForm1.txtHex3.Value) & ")" 

例如;input的值为文本框:#FF8800 – 结果:RGB(255,136,0)