【发布时间】:2009-02-06 14:53:55
【问题描述】:
我有一个电子表格,其中的单元格颜色很有意义。
有没有人知道如何在 Excel 工作表中返回当前单元格的背景颜色值?
【问题讨论】:
我有一个电子表格,其中的单元格颜色很有意义。
有没有人知道如何在 Excel 工作表中返回当前单元格的背景颜色值?
【问题讨论】:
你可以使用Cell.Interior.Color,我用它来计算一个范围内具有给定背景颜色(即匹配我的图例)的单元格的数量。
【讨论】:
如果您正在查看表格、数据透视表或具有条件格式的内容,您可以尝试:
ActiveCell.DisplayFormat.Interior.Color
这似乎也适用于常规单元格。
【讨论】:
也许你可以使用这个属性:
ActiveCell.Interior.ColorIndex - one of 56 preset colors
和
ActiveCell.Interior.Color - RGB color, used like that:
ActiveCell.Interior.Color = RGB(255,255,255)
【讨论】:
以下代码给出了范围的 HEX 和 RGB 值,无论是使用条件格式格式化还是其他方式。如果范围未使用条件格式格式化,并且您打算在 Excel 中使用 iColor 函数作为 UDF。它行不通。阅读以下来自MSDN 的摘录。
请注意,DisplayFormat 属性在用户定义的函数中不起作用。例如,在返回单元格内部颜色的工作表函数中,如果您使用类似于以下的行:
Range.DisplayFormat.Interior.ColorIndex
然后执行工作表函数以返回 #VALUE!错误。如果你没有找到条件格式范围的颜色,那么我鼓励你宁愿使用
Range.Interior.ColorIndex
那么该函数也可以用作 Excel 中的 UDF。如iColor(B1,"HEX")
Public Function iColor(rng As Range, Optional formatType As String) As Variant
'formatType: Hex for #RRGGBB, RGB for (R, G, B) and IDX for VBA Color Index
Dim colorVal As Variant
colorVal = rng.DisplayFormat.Interior.Color
Select Case UCase(formatType)
Case "HEX"
iColor = "#" & Format(Hex(colorVal Mod 256),"00") & _
Format(Hex((colorVal \ 256) Mod 256),"00") & _
Format(Hex((colorVal \ 65536)),"00")
Case "RGB"
iColor = Format((colorVal Mod 256),"00") & ", " & _
Format(((colorVal \ 256) Mod 256),"00") & ", " & _
Format((colorVal \ 65536),"00")
Case "IDX"
iColor = rng.Interior.ColorIndex
Case Else
iColor = colorVal
End Select
End Function
'Example use of the iColor function
Sub Get_Color_Format()
Dim rng As Range
For Each rng In Selection.Cells
rng.Offset(0, 1).Value = iColor(rng, "HEX")
rng.Offset(0, 2).Value = iColor(rng, "RGB")
Next
End Sub
【讨论】: