vba 获取 Excel 单元格背景颜色十六进制值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21597734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Excel cell background color hex value
提问by Radu Bompa
I would like to obtain the background color of a cell in an Excel sheet using a UDF formula or VBA. I found this UDF:
我想使用 UDF 公式或 VBA 获取 Excel 工作表中单元格的背景颜色。我找到了这个 UDF:
Public Function BColor(r As Range) As Long
BColor = r(1).Interior.ColorIndex
End Function
It can be used like this in a cell: =BColor(A1)
I'm not familiar with VBA, this returns some long value and I wonder if it is possible to obtain the hex value directly. Thank you!
它可以在单元格中这样使用:=BColor(A1)
我不熟悉 VBA,这会返回一些长值,我想知道是否可以直接获取十六进制值。谢谢!
回答by
try this
尝试这个
Function HexCode(Cell As Range) As String
HexCode = Right("000000" & Hex(Cell.Interior.Color), 6)
End Function
回答by Stu.tech
I tried the above code, but it returned a BGR value (as suggested)
我尝试了上面的代码,但它返回了一个 BGR 值(如建议的那样)
However, this code returns a RGB Hex value. I just can't get it to auto update.
但是,此代码返回 RGB 十六进制值。我只是无法让它自动更新。
Public Function HexCodeRGB(cell As Range) As String
HexCodeBGR = Right("000000" & Hex(cell.Interior.Color), 6)
HexCodeRGB = Right(HexCodeBGR, 2) & Mid(HexCodeBGR, 3, 2) & Left(HexCodeBGR, 2)
End Function
Good luck
祝你好运
回答by Sparker73
Based on the best voted answer, here is an example of a real case, my case. I supply it as a macro and a screenshots. I hope this can help someone out.
基于最佳投票答案,这里有一个真实案例的例子,我的案例。我将其作为宏和屏幕截图提供。我希望这可以帮助别人。
The VBA macro is simple but I'll paste it here. If you take a look at the attachment you will see that I have duplicated that column and cleared the color names in Spanish and titled the column "color", the I did run this macro:
VBA 宏很简单,但我会把它贴在这里。如果您查看附件,您会看到我复制了该列并清除了西班牙语中的颜色名称并将该列命名为“颜色”,我确实运行了这个宏:
Sub printHEXBGColor()
Set r = Range("myRange")
Dim HEXcolor As String
Dim i As Long
For i = 1 To r.Rows.Count
r.Cells(i, 1).Activate
HEXcolor = "#" + Right("000000" & Hex(ActiveCell.Interior.Color), 6)
ActiveCell = HEXcolor
Next i
End Sub