我需要使用条件格式从 Excel 获取单元格颜色。 单元格按条件格式规则着色,因此我无法直接读取背景颜色,因为它始终为 00000000。尝试过的库:openpyxl 和 pandas。
可以使用 VBA 函数读取条件格式单元格的填充值:
范围(“B2”)=范围(“A2”).DisplayFormat.Interior.Color
其中 A2 是格式化(源)单元格,B2 是您想要在其中获取颜色值的目标单元格。
我发现返回的小数需要一些处理 - 特别是对于原色(例如 RGB 255,0,0 仅返回 255 - 没有给出它是 0,255,0 还是 0,0,255 的指示)以及转换转换为十六进制会导致前导零或尾随零。
您可以通过以下方式解决此问题:
这将为您提供三对十六进制值,您可以使用:
rev_hex_fill = Right("000000" & Hex(Range("A2").DisplayFormat.Interior.Color), 6)
rev_hex_fill = 右(rev_hex_fill, 2) & 中(rev_hex_fill, 3, 2) & 左(rev_hex_fill,2)
范围(“B2”)= rev_hex_fill
您可以对字体颜色执行相同的操作,但不需要 DisplayFormat 部分 - 您可以只使用 Range("A2").Font.Color。
我刚刚完成了下面的代码,它循环、读取和显示最多 100 个条件格式的填充和字体颜色 (B3:B103),可能对社区有用。看起来我还不能添加图像,但一旦我在这里呆得更久,我会再做一次。
希望有帮助,
迈克尔
'迈克尔·惠勒和詹姆斯·邓肯 280324 '从条件格式中读取单元格和字体颜色,以便它们可以在其他地方使用
子 getcol()
For Row = 3 To 102
Source = ("B" & Row)
fill_cell = ("D" & Row)
Range(fill_cell).Interior.Color = Range(Source).DisplayFormat.Interior.Color
fill_text = ("E" & Row)
Range(fill_text).Font.Color = Range(Source).DisplayFormat.Interior.Color
font_fill = ("F" & Row)
Range(font_fill).Interior.Color = Range(Source).Font.Color
font_text = ("G" & Row)
Range(font_text).Font.Color = Range(Source).Font.Color
full_copy = ("H" & Row)
Range(full_copy).Interior.Color = Range(Source).DisplayFormat.Interior.Color
Range(full_copy).Font.Color = Range(Source).Font.Color
Range(full_copy) = Range(fill_text)
fill_dec = ("I" & Row)
Range(fill_dec) = Range(Source).DisplayFormat.Interior.Color
fill_hex = ("J" & Row)
rev_hex_fill = Right("000000" & Hex(Range(Source).DisplayFormat.Interior.Color), 6)
rev_hex_fill = Right(rev_hex_fill, 2) & Mid(rev_hex_fill, 3, 2) & Left(rev_hex_fill, 2)
Range(fill_hex) = rev_hex_fill
font_dec = ("K" & Row)
Range(font_dec) = Range(Source).Font.Color
font_hex = ("L" & Row)
rev_hex_text = Right("000000" & Hex(Range(Source).Font.Color), 6)
rev_hex_text = Right(rev_hex_text, 2) & Mid(rev_hex_text, 3, 2) & Left(rev_hex_text, 2)
Range(font_hex) = rev_hex_text
Next
结束子