programing

선택한 셀의 배경색 반환

mbctv 2023. 4. 21. 21:17
반응형

선택한 셀의 배경색 반환

셀이 의미 있게 색칠된 스프레드시트가 있습니다.

엑셀 시트에 있는 현재 셀의 배경색 값을 어떻게 반환할 수 있는지 아는 사람이 있나요?

사용할 수 있습니다.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)

다음 코드는 조건부 포맷을 사용하는지 여부에 관계없이 범위의 16진수 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

ActiveCell의 동일한 인덱스를 사용했는데도 셀 색상과 프리셋의 실제 색상을 맞추는 데 문제가 있었습니다.내부.ColorIndex.대신 위의 @jainashish 답변을 따라 각각의 RGB 값을 VBA 함수에 적용했습니다.

Dim colorVal As Variant
colorVal = tempFile.Worksheets("Dashboard").Range("F2").DisplayFormat.Interior.color

iColor = Format((colorVal Mod 256), "00") & ", " & _
    Format(((colorVal \ 256) Mod 256), "00") & ", " & _
    Format((colorVal \ 65536), "00")
iColorSplitRGB = Split(iColor, ",")
r = iColorSplitRGB(0)
g = iColorSplitRGB(1)
b = iColorSplitRGB(2)

tempFile.Worksheets("Dashboard").Range("B8").Interior.color = RGB(r, g, b)

언급URL : https://stackoverflow.com/questions/520570/return-background-color-of-selected-cell

반응형