vba 根据 Excel 2013 中的十六进制值用颜色填充单元格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24743199/
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
Fill a cell with color based on it's HEX value in Excel 2013
提问by Mathieu
I have a spreadsheet with cells in the A column containing colors in their HEX format. Is it possible to fill the adjacent cell automatically with the color matching the HEX value?
我有一个电子表格,其中 A 列中的单元格包含十六进制格式的颜色。是否可以使用与 HEX 值匹配的颜色自动填充相邻单元格?
From the research done until now I understand the VBA should first convert the HEX string to it's RGB correspondent and then fill the cell color with the result.
从研究到现在,我明白 VBA 应该首先将 HEX 字符串转换为它的 RGB 对应物,然后用结果填充单元格颜色。
E.g.: if A1 contains the value "7fcac3" (or "#7fcac3" but I don't think the pound is required), the VBA should fill the adjacent B cell with RGB (127,202,195).
例如:如果 A1 包含值“7fcac3”(或“#7fcac3”,但我认为不需要磅),VBA 应该用 RGB (127,202,195) 填充相邻的 B 单元格。
Below is an example of how the VBA might look, found (here). The problem is that I get a "Compile Error: Invalid outside procedure"error in Excel 2013.
下面是 VBA 外观的示例,找到(here)。问题是我在 Excel 2013 中收到“编译错误:外部过程无效”错误。
For i = 1 To LastRow
Sub SetHexColors()
Dim i, LastRow
LastRow = Range("A" & Rows.Count).End(xlUp).Row
For i = 1 To LastRow
Cells(i, "B").Interior.Color = HEXCOL2RGB(Cells(i, "A"))
Next
End Sub
Public Function HEXCOL2RGB(ByVal HexColor As String) As String
Dim Red As String, Green As String, Blue As String
HexColor = Replace(HexColor, "#", "")
Red = Val("&H" & Mid(HexColor, 1, 2))
Green = Val("&H" & Mid(HexColor, 3, 2))
Blue = Val("&H" & Mid(HexColor, 5, 2))
HEXCOL2RGB = RGB(Red, Green, Blue)
End Function
Many thanks, Mathieu
非常感谢,马修
采纳答案by Mark Balhoff
The first line of code:
第一行代码:
For i = 1 To LastRow
is not in the inside of a Sub or Function. Looks like that is a copy of a line you already have in the Sub SetHexColors so I would expect you just need to comment out or delete that first line. The only lines of code you can put outside Subs and Functions are variable declarations and things like Option statements (e.g., Option Explicit)
不在 Sub 或 Function 的内部。看起来这是您在 Sub SetHexColors 中已有的行的副本,所以我希望您只需要注释掉或删除第一行。唯一可以放在 Subs 和 Functions 之外的代码行是变量声明和诸如 Option 语句之类的东西(例如,Option Explicit)