返回所选单元格的背景颜色

whi*_*hiz 23 excel vba excel-vba

我有一个电子表格,其中的单元格有意义地着色.

有没有人知道如何在Excel工作表中返回当前单元格的背景颜色值?

Gar*_*ler 26

您可以使用Cell.Interior.Color,我用它来计算具有给定背景颜色的范围中的单元格数(即匹配我的图例).


RPh*_*der 15

如果您正在查看表,数据透视表或具有条件格式的内容,您可以尝试:

ActiveCell.DisplayFormat.Interior.Color
Run Code Online (Sandbox Code Playgroud)

这似乎也适用于常规细胞.


Ant*_*ton 7

也许你可以使用这个属性:

ActiveCell.Interior.ColorIndex - one of 56 preset colors
Run Code Online (Sandbox Code Playgroud)

ActiveCell.Interior.Color - RGB color, used like that:

ActiveCell.Interior.Color = RGB(255,255,255)
Run Code Online (Sandbox Code Playgroud)


jai*_*ish 5

下面的代码给出了范围的HEXRGB值,无论是使用条件格式还是其他格式。如果范围未使用条件格式进行格式化,并且您打算在 Excel 中将 iColor 函数用作 UDF。它不会工作。阅读以下摘录自MSDN

请注意,DisplayFormat属性在用户定义的函数中不起作用。例如,在返回单元格内部颜色的工作表函数中,如果您使用类似于以下内容的行:

Range.DisplayFormat.Interior.ColorIndex
Run Code Online (Sandbox Code Playgroud)

然后执行工作表函数以返回 #VALUE!错误。如果您没有找到条件格式范围的颜色,那么我鼓励您宁可使用

Range.Interior.ColorIndex
Run Code Online (Sandbox Code Playgroud)

那么该函数也可以用作 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
Run Code Online (Sandbox Code Playgroud)