如何使用VBA识别选定单元格的长颜色或十六进制颜色?使用 Font.TextColor 或 Hex(cell.Font.color),或者?

问题描述 投票:0回答:1

如何使用 VBA Excel 报告选定单元格的字体颜色代码或十六进制? 下面的 1. 序列和 2. 函数对于获取阴影颜色非常有效。 但在下面的第三个例程中,用“Font”替换“Shade”一词时不起作用, 我无法使用 Font.TextColor 或 Hex(cell.Font.color) 来识别字体颜色。 向 1. 和 2. 中的阴影颜色代码设计者竖起大拇指,如果我们可以在 3. 中使用字体做同样的事情,那就太好了。

1

Sub ShadClipbdCopyHex_CtlSftT()
'   Got Shade Hex, need font details as well
'   https://stackoverflow.com/questions/76344840/how-to-get-rgb-colors-or-hex-colors-out-of-word-using-vb
    ' Declare variables
    Dim ShadeColor As Long
    Dim fontName As String
    Dim ShadeHex As String
            ShadeColor = ActiveCell.Interior.color
            ShadeHex = ConvertLongToHex(ShadeColor)
'            fontName = ActiveCell.Font.Name
        Clipboard ShadeHex
        Debug.Print ShadeHex ', fontName
End Sub

2

Public Function ConvertLongToHex(lColor As Long) As String
    Dim sRed As String, sGreen As String, sBlue As String
    sRed = Right("00" & Hex(lColor Mod 256), 2)
    sGreen = Right("00" & Hex(lColor \ 2 ^ 8 Mod 256), 2)
    sBlue = Right("00" & Hex(lColor \ 2 ^ 16 Mod 256), 2)
    ConvertLongToHex = "#" & sRed & sGreen & sBlue
End Function

3

Sub FontClipbdCopyHex()
'   CP 45Mar24 Got Shade Hex above, adapting to Fonts substituting Font.TextColor
'   https://learn.microsoft.com/en-us/office/vba/api/Word.Font.TextColor

    Dim FontColor As Long
    Dim fontName As String
    Dim FontHex As String

            FontColor = ActiveCell.Font.TextColor
            FontHex = ConvertLongToHex(FontColor)
'            fontName = ActiveCell.Font.Name
        Clipboard FontHex
        Debug.Print FontHex ', fontName
End Sub
excel vba colors fonts identify
1个回答
0
投票

ActiveCell.Font.Color
将返回代表颜色的数字。

但请注意,它返回的是 BGR 值,而不是 RGB 值。考虑到颜色值是使用 RGB() 函数设置的,这似乎很奇怪,但实际上该函数返回一个表示 BGR 值的数字。

例如下面的代码

Sub test()
    ActiveCell.Font.Color = RGB(0, 0, 255)
    Debug.Print Hex(RGB(0, 0, 255)) & ", " & RGB(0, 0, 255)
    Debug.Print Hex(ActiveCell.Font.Color) & ", " & ActiveCell.Font.Color
End Sub

在中间窗口中生成以下内容:

FF0000, 16711680
FF0000, 16711680

在此示例中,该单元格中的文本颜色是蓝色,而不是红色。

© www.soinside.com 2019 - 2024. All rights reserved.