Excel получить цвет rgb

 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

#1

29.04.2015 12:39:26

Уважаемые форумчане, можно получить цвет заливки ячейки Excel таким образом:

Код
 Set R = Range("A1")
 x1 = R.Interior.Color 'в цифровом формате, например белый -"16777215"
 x2 = Hex$(x1) 'в шестнадцатеричном выражении - "FFFFFF" 
 x3 = "&H00" & x2 & "&" ' в формате H00+Hex - "&H00FFFFFF&" -используются в пользовательских формах Excel

Как получить в формате RGB (255,255,255), т.е. R=255, G=255, B=255?

Изменено: bedvit29.04.2015 12:45:13

«Бритва Оккама» или «Принцип Калашникова»?

 

Hugo

Пользователь

Сообщений: 23249
Регистрация: 22.12.2012

#2

29.04.2015 12:55:42

У себя в заметках нашёл такое (файл не качается…):

Код
Если необходимо вычислить RGB, то это делается так:
(фрагмент из файла Уокенбаха, пример здесь: http://www.planetaexcel.ru/docs/forum_upload/post_74452.xls)

Dim HexDigits As String
Dim BluePart As Integer, GreenPart As Integer, RedPart As Integer
UserForm1.SampleLabel.BackColor = ColorButton.BackColor
HexDigits = Hex(ColorButton.BackColor)
Do Until Len(HexDigits) = 6
HexDigits = "0" & HexDigits 'pad with zeros
Loop
BluePart = Val("&h" & Left(HexDigits, 2))
GreenPart = Val("&h" & Mid(HexDigits, 3, 2))
RedPart = Val("&h" & Right(HexDigits, 2))
UserForm1.RGBLabel.Caption = RedPart & " " & GreenPart & " " & BluePart

 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

#3

29.04.2015 14:06:53

Hugo, использовал Ваши данные, вышло следующее:

Код
...
Set R = Range("A1") 'вводим нужную ячейку
x1 = R.Interior.Color 'в цифровом формате, например белый -"16777215"
x2 = Hex$(x1) 'в шестнадцатеричном выражении - "FFFFFF"
Do Until Len(x2) = 6
x2 = "0" & x2 'догоняем 6 знаков нулями
DoEvents
Loop
x3 = "&H00" & x2 & "&" ' в формате H00+Hex - "&H00FFFFFF&" -используются в пользовательских формах Excel
R = Val("&h" & Right(x2, 2))
G = Val("&h" & Mid(x2, 3, 2))
B = Val("&h" & Left(x2, 2))
'Debug.Print R & " " & G & " " & B  'или MsgBox R & " " & G & " " & B    '-посмотреть... 
...

Спасибо!

Изменено: bedvit29.04.2015 14:10:22

«Бритва Оккама» или «Принцип Калашникова»?

 

Hugo

Пользователь

Сообщений: 23249
Регистрация: 22.12.2012

#4

29.04.2015 15:20:44

Не понял зачем там такое сложное

Код
Do Until Len(HexDigits) = 6
HexDigits = "0" & HexDigits 'pad with zeros
Loop

когда можно просто

Код
HexDigits = Right("000000" & HexDigits, 6)
 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

«Бритва Оккама» или «Принцип Калашникова»?

 

Слэн

Пользователь

Сообщений: 5192
Регистрация: 16.01.2013

#6

29.04.2015 16:05:07

так R.Interior.Color это запись rgb в виде (r+g*256+ b*256^2)

таким образом:

Код
Function rgb_(Rng)
Dim x, r, g, b
x = Rng.Interior.Color
b = Int(x / 65536)
x = x - b * 65536
g = Int(x / 256)
r = x - g * 256
rgb_ = "(" & r & "," & g & "," & b & ")"
End Function
Sub q()
ActiveCell.Interior.Color = rgb(125,128,200)
MsgBox rgb_(ActiveCell)
End Sub

Изменено: Слэн29.04.2015 16:07:08

Живи и дай жить..

 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

#7

29.04.2015 18:42:10

Слэн, отлично!
Hugo, Слэн, коллеги по Excel, кому интересна эта тема ))…
…набросал небольшую форму перевода из одной системы цветов в другую. (см. вложение)

Прикрепленные файлы

  • Цвет.xlsb (32.26 КБ)

Изменено: bedvit29.04.2015 18:45:42

«Бритва Оккама» или «Принцип Калашникова»?

Here are some small functions for you. From your sheet, press AltF11 to reach the VBA editor, insert a new module, paste the below code, go back to your worksheet and use them by their names, like in =FillColor(A1)

The first two are the promised «3-liners» giving decimal values for font and background colors — not very useful though

The second pair converts the decimal number to RGB and returns a string of format N, N, N

The third pair are array formulas — select 3 cells in a row, enter the formula and press Ctrl+Shift+Enter to obtain numeric RGB values in 3 neighboring cells

Function FillColor(Target As Range) As Variant
    FillColor = Target.Interior.Color
End Function

Function FontColor(Target As Range) As Variant
    FontColor = Target.Font.Color
End Function

Function FillColorRGB(Target As Range) As Variant
Dim N As Double

    N = Target.Interior.Color
    FillColorRGB = Str(N Mod 256) & ", " & Str(Int(N / 256) Mod 256) & ", " & Str(Int(N / 256 / 256) Mod 256)
End Function

Function FontColorRGB(Target As Range) As Variant
Dim N As Double

    N = Target.Font.Color
    FontColorRGB = Str(N Mod 256) & ", " & Str(Int(N / 256) Mod 256) & ", " & Str(Int(N / 256 / 256) Mod 256)
End Function

Function FillColorRGBArray(Target As Range) As Variant
Dim N As Double, A(3) As Integer

    N = Target.Interior.Color
    A(0) = N Mod 256
    A(1) = Int(N / 256) Mod 256
    A(2) = Int(N / 256 / 256) Mod 256
    FillColorRGBArray = A
End Function

Function FontColorRGBArray(Target As Range) As Variant
Dim N As Double, A(3) As Integer

    N = Target.Font.Color
    A(0) = N Mod 256
    A(1) = Int(N / 256) Mod 256
    A(2) = Int(N / 256 / 256) Mod 256
    FontColorRGBArray = A
End Function

A word of caution: changing the color of a cell does not start recalculation by the above functions/formulas, as recoloring a cell in general is not supposed to drive recalculation. You have to manually start a full recalculation using Ctrl+Alt+Shift+F9

Конвертация цвета из числового значения Long в RGB формат из кода VBA Excel с помощью пользовательской функции ColorLongToRGB. Примеры.

Функция ColorLongToRGB

Пользовательская функция ColorLongToRGB по своему действию является обратной для встроенной в VBA Excel функции RGB, которая значения цветов по системе RGB переводит в значения типа Long.

Для конвертации цвета из Long в RGB нам понадобится функция Windows API CopyMemory (копирование блока памяти из одного расположения в другое), которую следует объявить в разделе Declarations стандартного модуля:

Declare PtrSafe Sub CopyMemory Lib «kernel32» Alias «RtlMoveMemory» (Destination As Any, Source As Any, ByVal Length As LongPtr)

Это вариант для 64-разрядных версий VBA Excel, для 32-разрядных платформ из объявления следует убрать ключевое слово PtrSafe и, возможно, тип данных LongPtr заменить на Long.

Параметры функции CopyMemory:

  • Destination — указатель на начальный адрес места назначения скопированного блока;
  • Source — указатель на начальный адрес копируемого блока памяти;
  • Длина — размер копируемого блока памяти в байтах.

Кроме того, нам понадобится переменная пользовательского типа данных, которую следует объявить в разделе Declarations:

Type myRGB

    r As Byte

    g As Byte

    b As Byte

End Type

Элементы пользовательского типа данных myRGB:

  • r — интенсивность красного цвета;
  • g — интенсивность зеленого цвета;
  • b — интенсивность синего цвета.

Код функции ColorLongToRGB, предназначенной для конвертации цвета из Long в RGB:

Function ColorLongToRGB(d As Long) As myRGB

    CopyMemory ColorLongToRGB, d, 3

End Function

d — числовое значение цвета типа Long.

В данном случае, числовое значение цвета типа Long распознается как массив из четырех байтов, значение первого из которых соответствует интенсивности красного цвета, второго — интенсивности зеленого цвета, третьего — интенсивности синего цвета. Четвертый байт может содержать значение альфа-канала (информация о прозрачности рисунка), который в Excel не используется.

Функция ColorLongToRGB с помощью функции Windows API CopyMemory копирует массив из первых трех байтов числового значения цвета в три элемента пользовательского типа данных myRGB (r, g, b).

Код функции ColorLongToRGB в сборке с объявлением функция Windows API CopyMemory и пользовательского типа данных myRGB:

Declare PtrSafe Sub CopyMemory Lib «kernel32» Alias «RtlMoveMemory» (Destination As Any, Source As Any, ByVal Length As LongPtr)

Type myRGB

    r As Byte

    g As Byte

    b As Byte

End Type

Function ColorLongToRGB(d As Long) As myRGB

    CopyMemory ColorLongToRGB, d, 3

End Function

Пример 1

Проверка работоспособности пользовательской функции ColorLongToRGB:

Sub Primer1()

Dim x As myRGB, a As Long

a = RGB(red:=120, green:=200, blue:=150)

x = ColorLongToRGB(a)

MsgBox «r = « & x.r & vbNewLine & «g = « & x.g & vbNewLine & «b = « & x.b

End Sub

Результат работы кода:

Пример 2

Есть таблица, первый столбец которой заполнен произвольными цветами:

Необходимо числовой код каждого цвета типа Long преобразовать в RGB формат и заполнить его элементами пустые ячейки таблицы.

Код VBA Excel для решения данной задачи:

Sub Primer2()

Dim x As myRGB, myCell As Range

    For Each myCell In Range(«A2:A6»)

        x = ColorLongToRGB(myCell.Interior.Color)

        myCell.Offset(0, 1) = x.r

        myCell.Offset(0, 2) = x.g

        myCell.Offset(0, 3) = x.b

    Next

End Sub

Результат работы кода:

Пример 3

Пример функции ColorLongToRGBA c альфа-каналом в сборке с объявлением функция Windows API CopyMemory и пользовательского типа данных myRGBA:

Declare PtrSafe Sub CopyMemory Lib «kernel32» Alias «RtlMoveMemory» (Destination As Any, Source As Any, ByVal Length As LongPtr)

Type myRGBA

    r As Byte

    g As Byte

    b As Byte

    a As Byte

End Type

Function ColorLongToRGBA(d As Long) As myRGBA

    CopyMemory ColorLongToRGBA, d, 4

End Function

Элемент a пользовательского типа данных myRGBA — это альфа-канал, который содержит информацию о прозрачности рисунка.


Преобразование цветов в RGB и обратно

t330

Дата: Четверг, 16.05.2019, 18:29 |
Сообщение № 1

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 147


Репутация:

0

±

Замечаний:
20% ±


Excel 2016

Всем привет.
Во вложении файлик с функцией получения из десятичного значения цвета, цвета в формате RGB

Насколько я знаю десятичное значение цвета ColorVal из RGB получается по формуле:
ColorVal = 255^0*R + 255^1 * G + 255^2 * B

а как отсюда отбратно вычленить R , G и B ?

В функции ниже вычленение происходит по такой формуле (Загадка! как они их ОДНОГО уравнения с тремя неизвестными нашли эти три неизвестные):

R= ColorVal 256 ^ 0 And 255
G = ColorVal 256 ^ 1 And 255
B= ColorVal 256 ^ 2 And 255

Кто может объяснить , что делает оператор AND 255 в этих формулах?

[vba]

Код

Function DECIMAL2RGB(ColorVal) As Variant
‘   Converts a color value to an RGB triplet
‘   Returns a 3-element variant array
    DECIMAL2RGB = Array(ColorVal 256 ^ 0 And 255, ColorVal 256 ^ 1 And 255, ColorVal 256 ^ 2 And 255)
End Function

[/vba]

 

Ответить

bmv98rus

Дата: Четверг, 16.05.2019, 19:32 |
Сообщение № 2

Группа: Друзья

Ранг: Участник клуба

Сообщений: 4009


Репутация:

760

±

Замечаний:
0% ±


Excel 2013/2016

255 это 11111111 в двоичном виде
AND в данном случае производит побитное логическое И
и например 85,85,85 буде закодировано как
010101001010101101010101 ( 5 548 885‬)‬
000000000000000011111111
===================
000000000000000001010101 (85)
делением на 256 просто сдвигаеются разряды на 8 бит.

000000000101010101010101 (21 845)‬
000000000000000011111111
===================
000000000000000001010101 (85)

000000000000000001010101 (21 845)‬
000000000000000011111111
===================
000000000000000001010101 (85)

каждый цвет закодирован в 8 разрядах. Вот и весь фокус.


Замечательный Временно просто медведь , процентов на 20.

 

Ответить

krosav4ig

Дата: Четверг, 16.05.2019, 20:13 |
Сообщение № 3

Группа: Друзья

Ранг: Старожил

Сообщений: 2346


Репутация:

989

±

Замечаний:
0% ±


Excel 2007,2010,2013

что делает оператор AND 255 в этих формулах?

Извлекает младший байт
[vba]

Код

Function DECIMAL2RGB(ColorVal) As Variant
‘   Converts a color value to an RGB triplet
‘   Returns a 3-element variant array
    With Application
        DECIMAL2RGB = .Bitand(.Bitrshift(ColorVal, Array(0, 8, 16)), &HFF)
    End With
End Function

[/vba]


email:krosav4ig26@gmail.com WMR R207627035142 WMZ Z821145374535 ЯД 410012026478460

 

Ответить

t330

Дата: Суббота, 18.05.2019, 01:05 |
Сообщение № 4

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 147


Репутация:

0

±

Замечаний:
20% ±


Excel 2016

000000000000000001010101 (21 845)‬
000000000000000011111111
===================
000000000000000001010101 (85)

каждый цвет закодирован в 8 разрядах. Вот и весь фокус.

Спасибо за ответ.
У вас нет ошибки ? Почему в последнем И в скобках 21845 ?

И еще вопрос:

делением на 256 просто сдвигаеются разряды на 8 бит.

Зачем сдвигать на 8 бит разряды?

 

Ответить

t330

Дата: Суббота, 18.05.2019, 01:14 |
Сообщение № 5

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 147


Репутация:

0

±

Замечаний:
20% ±


Excel 2016

Спасибо за ответ.
Видимо это очевидно для профи, но я -пока чайник и не понял эту строку.

DECIMAL2RGB = .Bitand(.Bitrshift(ColorVal, Array(0, 8, 16)), &HFF)

Справка показала , что функция Bitshift(x,y) сдвигает битовое Х на Y разрядов.
У вас в формуле вместо Y стоит массив Array (0,8,16) а не число… Это как?
И еще непонятно , что такое &HFF …

Понимаю, что может быть это глупые вопросы и если скучно разжевывать , то все равно спасибо за ответ.

 

Ответить

bmv98rus

Дата: Суббота, 18.05.2019, 12:16 |
Сообщение № 6

Группа: Друзья

Ранг: Участник клуба

Сообщений: 4009


Репутация:

760

±

Замечаний:
0% ±


Excel 2013/2016


да, копипэст подвел, там 85

Разряды сдвигать чтоб получить именно те 8 бит чем закодирован следующий цвет.


Замечательный Временно просто медведь , процентов на 20.

 

Ответить

t330

Дата: Воскресенье, 19.05.2019, 20:35 |
Сообщение № 7

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 147


Репутация:

0

±

Замечаний:
20% ±


Excel 2016

Разряды сдвигать чтоб получить именно те 8 бит чем закодирован следующий цвет.

Что-то я запутался.

RGB — это представление цвета в виде трех байтов по 8 бит.

То есть Цвет в RGB формате можно записать так:

Цвет = rrrrrrrgggggggbbbbbbbb (8 бит для оттенков Red, потом 8бит для оттенков Gren и потом 8 бит для оттенков Blue ИТОГО 24 бита)

Чтобы вычленить из Цвета отдельные Байты для Red Green и Blue , нужно сделать следующее:

Чтобы получить старшие 8 бит для Red = rrrrrrrr нужно арифметически сдвинуть вправо на 16 разрядов весь Цвет= rrrrrrrgggggggbbbbbbbb , что эквивалентно побитовому делению на 256^2

Чтобы получить вторые 8 бит для Green = gggggggg нужно
сначала арифметически сдвинуть вправо на 8 разрядов Цвет= rrrrrrrgggggggbbbbbbbb , что эквивалентно побитовому делению на 256
а далее полученное после сдвига значение rrrrrrrggggggg обрезать до последних 8 битов через оператор логического И
то есть rrrrrrrggggggg AND 255 = ggggggg = Green

Чтобы получить самые младшие 8 бит для Blue = bbbbbbbb нужно
просто значение Цвета = rrrrrrrgggggggbbbbbbbb обрезать до последних 8 битов через оператор логического И
то есть rrrrrrrgggggggbbbbbbbb AND 255 = bbbbbbbb = Blue

Если я все правильно понял , то тогда почему в коде

[vba]

Код

DECIMAL2RGB = Array(ColorVal 256 ^ 0 And 255, ColorVal 256 ^ 1 And 255, ColorVal 256 ^ 2 And 255)

[/vba]

первое значение в массиве = ColorVal 256 ^ 0 And 255 — это Red , а не Blue ?
Должно же быть наоборот!

ColorVal 256 ^ 0 And 255 расшифровывается как выборка из значения Colorval младших 8 битов , то есть цвет BLUE, а не REd…

Либо я где-то ошибаюсь, либо в файлу Уокенбаха ошибка…

 

Ответить

krosav4ig

Дата: Понедельник, 20.05.2019, 13:50 |
Сообщение № 8

Группа: Друзья

Ранг: Старожил

Сообщений: 2346


Репутация:

989

±

Замечаний:
0% ±


Excel 2007,2010,2013

t330, в VB цвет в шестнадцатеричном представлении кодируется в виде &Hbbggrr, в HTML в виде #rrggbb

Шестнадцатеричное представление числа 255, по совместительству RGB(255,0,0), vbRed
t330, в VB цвет в шестнадцатеричном представлении кодируется в виде &Hbbggrr, в HTML в виде #rrggbb

в формуле вместо Y стоит массив Array (0,8,16) а не число… Это как?

в коде я использовал вызов функции листа БИТ.СДВИГП и БИТ.И (Bitrshift и Bitand соответсвенно), только забыл указать, что работает только начиная с Excel 2013. Вызов функций листа в vba в контексте Application позволяет предоставлять им массивы в качестве аргументов (в отличие от вызова в контексте WorksheetFunction).


email:krosav4ig26@gmail.com WMR R207627035142 WMZ Z821145374535 ЯД 410012026478460

Сообщение отредактировал krosav4igПонедельник, 20.05.2019, 15:49

 

Ответить

t330

Дата: Понедельник, 20.05.2019, 14:15 |
Сообщение № 9

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 147


Репутация:

0

±

Замечаний:
20% ±


Excel 2016

Спасибо, начал понимать.

Осталось разобраться с фразой:

Шестнадцатеричное представление числа 255, по совместительству RGB(0,0,255), vbRed

То есть, RGB(0,0,255) — это RED?

Вот тут http://x-phantom.ru/zhtml/tablica_cvetov_html.php пишут , что RGB(0,0,255) — это не RED , а BLUE

Или в VB все наоборот?

 

Ответить

RAN

Дата: Понедельник, 20.05.2019, 15:02 |
Сообщение № 10

Группа: Друзья

Ранг: Экселист

Сообщений: 5645

[vba]

Код

ActiveCell.Interior.Color = rgb(0,0,255)

[/vba]


Быть или не быть, вот в чем загвоздка!

 

Ответить

t330

Дата: Понедельник, 20.05.2019, 15:30 |
Сообщение № 11

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 147


Репутация:

0

±

Замечаний:
20% ±


Excel 2016

ActiveCell.Interior.Color = rgb(0,0,255)

Спасибо.
RGB (0,0,255) — это BLUE.

То есть в RGB последние 8 бит — это BLUE
Тогда почему для получения BLUE выполняется сдвиг вправо на 16 разрядов в формуле ColorVal 256 ^ 2 And 255 ?
Ведь BLUE — это последние 8 бит из 24 битного RGB числа?

По логике чтобы получить последние 8 бит для BLUE формула должна быть без всяких сдвигов вот такая: ColorVal And 255

 

Ответить

t330

Дата: Понедельник, 20.05.2019, 15:43 |
Сообщение № 12

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 147


Репутация:

0

±

Замечаний:
20% ±


Excel 2016

В общем сдается мне, что в RGB в побитовом формате расположение цветов идет вот по такой схеме:

bbbbbbb gggggggg rrrrrrrr
то есть сначала идут 8 бит оттенков BLUE
затем идут 8 бит оттенков Green
затем идут 8 бит оттенков Red

BLUE -GREEN- RED
а не RED — GREEN-BLUE

Например:
берем rgb(0,0,255)
в десятичном формате это 16 711 680

в двоичном формате — это 11111111 00000000 00000000

Отсюда видно ,что первые 8 бит = 11111111 — это и есть BLUE , а не RED

ПЦ…
Зачем они так сделали? RGB в двоичном виде оказывается BGR … чтобы людей запутать наверное)))

 

Ответить

krosav4ig

Дата: Понедельник, 20.05.2019, 15:43 |
Сообщение № 13

Группа: Друзья

Ранг: Старожил

Сообщений: 2346


Репутация:

989

±

Замечаний:
0% ±


Excel 2007,2010,2013

пишут , что RGB(0,0,255) — это не RED , а BLUE

ну там же про HTML коды цвета пишут

вот, например, RGB(196,212,72)
в js получение html кода цвета можно написать так
[vba]

Код

((196*256<<8)+212*256+72).toString(16) //результат — c4d448

[/vba]
в excel vba hex представление цвета
[vba]

Код

application.dec2hex(rgb(196,212,72),6) ‘результат — 48D4C4

[/vba]


email:krosav4ig26@gmail.com WMR R207627035142 WMZ Z821145374535 ЯД 410012026478460

Сообщение отредактировал krosav4igПонедельник, 20.05.2019, 15:53

 

Ответить

krosav4ig

Дата: Понедельник, 20.05.2019, 15:50 |
Сообщение № 14

Группа: Друзья

Ранг: Старожил

Сообщений: 2346


Репутация:

989

±

Замечаний:
0% ±


Excel 2007,2010,2013

То есть, RGB(0,0,255) — это RED?

это мой глюк, думаю про младший байт, пишу 255 справа…
Исправил в посте


email:krosav4ig26@gmail.com WMR R207627035142 WMZ Z821145374535 ЯД 410012026478460

 

Ответить

t330

Дата: Понедельник, 20.05.2019, 16:19 |
Сообщение № 15

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 147


Репутация:

0

±

Замечаний:
20% ±


Excel 2016

Всем спасибо, вроде допетрил:)

 

Ответить

I often find myself converting between different formats of color codes; especially from hex to RGB and back again. Rather than firing up Google and searching for color conversion tools online, I decided to write my own User Defined Functions in Excel, now I can calculate the result within a worksheet instead.

The functions in this post include the conversions for RGB, hex, HSL, HSV, CMYK and long formats.

Using these color conversion functions, I created an add-in that makes the conversion even easier. Keep reading to find out how you can download the add-in for free.

Download the example file: Click the link below to download the example file used for this post:

The downloads include:

  • 0006 Convert color codes.xlsm – includes all the custom functions
  • ColorCodeConverter.xlam – Excel add-in for color conversion
  • Add-in installation instructions.pdf – Add-in installation & xlsm unblocking instructions

Excel’s different color code formats

Even in Excel, there are four different methods of defining color; RGB, hex, HSL and long.

RGB

The RGB (Red, Green and Blue) color code is used within the standard color dialog box.

RGB Color Mode

The individual colors Red, Green and Blue each have 256 different shades, which when mixed can create 16,777,216 different color combinations.

HSL

Within the standard color dialog box there is another code format; using the color model drop-down we can change to HSL. HSL uses Hue, Saturation and Luminance to create the color.

HSL Color Mode

HSL tries to define colors closer to the way humans think about colors.

  • Hue – is the degree on the color wheel from 0 to 360. 0 is red, 120 is green, 240 is blue.
  • Saturation – is a percentage of the amount of color included. 100% is full color, 0% is no color (i.e. all grey)
  • Luminance (or lightness) – is a percentage of grey. 0% is black, 100% is white.

Frustratingly, Excel does not handle HSL in the standard way. Instead, Excel measures all the numbers where 0 is the lowest and 255 is the biggest. But, it’s a quirk we can handle.

Long

The long color code is used by VBA when displaying the color property of an item. The following macro displays the long code for the fill of the active cell.

Sub ActiveCellColor()

MsgBox "Long color code: " & ActiveCell.Interior.Color

End Sub

Select a cell and run the macro.

Long color code in a message box

The long code is a number from 0 to 16,777,215, where each separate number represents a color. The relationship between RGB and long is based on a simple calculation:

Long = Blue x 256 x 256 + Green x 256 + Red

As an example:

  • Where Red: 33, Green: 115 and Blue: 70
  • The result calculates as 70 x 256 x 256 + 115 x 256 + 33 = 4,616,993

Long and RGB are related; they are just different ways of calculating the same number.

Hex

Hex (which is short for hexadecimal) color codes are found in two places in Excel.

  • Color picker – Excel 2021 and Excel 365
  • VBA – All versions of Excel

HEX Color Mode

Since the introduction of hex codes in the color picker, there is now native conversion between RGB, Hex and HSL color codes.

Hex color codes are similar to RGB as they also use 256 shades for each individual color. The critical difference is that the hex system represents the numbers from 0 to 255 using just two characters. This is possible because hex uses Base-16.

We generally use Base-10 in everyday life, which means that we have 10 digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) available. As an example, the number 14 is created by using the formula (1 x base) + 4. The base is 10, so the result is calculated as (1 x 10) + 4, which equals 14.

For Base-16, there are 16 digits; however, as we don’t have enough number characters we use A, B, C, D, E and F to represent the numbers from 10 through 15.

As an example, the hex number AB equals 171.

  • A = 10
  • B = 11.
  • The calculation is (A x base) + B = (10 x 16) + 11 = 171

In hex, the lowest value is zero and the highest value is F (which is equal to 15). Therefore, there are 16 possible individual digits. This means that from two digits we can create 256 shades (16 x 16 = 256), which is the same as RGB. Therefore, hex also has the same 16,777,216 combinations as RGB and long.

Hex codes are presented in same order to RGB, so if the hex color code is #467321 the first two characters represent red, the middle two characters represent green and the last two are blue.

Using the #467321 hex code as an example, the conversion to RGB would be:

  • Red: Hex value of 46 calculates as (4 * 16) + 6 = 70
  • Green: Hex value of 73 calculates as (7 * 16) + 3 = 115
  • Blue: Hex value of 21 calculates as (2 * 16) + 1 = 33

The hex codes are used within the VBA properties to define color.

Hex code used within VBA

The color code in the screenshot above is: &H00467321&. However, there is a very subtle difference when using the VBA code; the hex code needs to be reversed. The first two characters represent blue, the middle two characters represent green and last two are blue.

Normally, blue would be #0000FF, but for the VBA property the code would be: &H00FF0000&

  • & = Start character
  • H = Hex code
  • 00 = Tells VBA to use a custom color
  • FF0000 = the Hex color code with the RGB reversed
  • & = End character

CMYK

Another common color code system is CMYK. It is used primarily for printing, as it determines the amount of Cyan, Magenta, Yellow and blacK ink used in overlapping printed dots.

While Excel does not use CMYK, it is a common method, so I have included it within the scope of this post.

HSV

Finally, to complete the spectrum of color code systems, there is HSV. It is similar to HSL, but it uses Hue, Saturation, and Value as measures. This is not just HSL under a different name. While Hue is the same under both systems, Saturation and Value both calculate as different values.

Excel does not support HSV, but is included below because it is a common method.

User Defined Functions for color conversion

In the section above, I’ve tried to explain how each method defines colors, but converting between them is a different matter entirely, and is much harder. Thankfully, we can let Excel do the work for us. Below are the UDF’s to convert between the various methods.

REMEMBER! – To use VBA functions, the code must be included in a standard VBA code module.

RGB, hex and long are all based on whole numbers, so they should perfectly convert between each other. CMYK and HSL involve decimal places and percentages and therefore could create small differences in their conversions.

Convert from RGB to hex

The following UDF calculates the hex value based on the RGB color codes.

Function GetHexFromRGB(Red As Integer, Green As Integer, Blue As Integer) As String

GetHexFromRGB = "#" & VBA.Right$("00" & VBA.Hex(Red), 2) & _
    VBA.Right$("00" & VBA.Hex(Green), 2) & VBA.Right$("00" & VBA.Hex(Blue), 2)

End Function

How to use the function:

The function contains 3 arguments, values between 0 and 255 for each individual Red, Green, or Blue value.

Hex from RGB

Convert from hex to RGB

The UDF below provides the Red, Green, or Blue value based on the hex color.

Function GetRGBFromHex(hexColor As String, RGB As String) As String

hexColor = VBA.Replace(hexColor, "#", "")
hexColor = VBA.Right$("000000" & hexColor, 6)

Select Case RGB

    Case "B"
        GetRGBFromHex = VBA.Val("&H" & VBA.Mid(hexColor, 5, 2))

    Case "G"
        GetRGBFromHex = VBA.Val("&H" & VBA.Mid(hexColor, 3, 2))

    Case "R"
        GetRGBFromHex = VBA.Val("&H" & VBA.Mid(hexColor, 1, 2))

End Select

End Function

How to use the function:

The function contains 2 arguments;

  1. the hex code
  2. the letter R, G or B, to represent the color to be returned

RGB from Hex

Convert from RGB to long

This UDF provides the long value based on the RGB color codes.

Function GetLongFromRGB(Red As Integer, Green As Integer, Blue As Integer) As Long

GetLongFromRGB = RGB(Red, Green, Blue)

End Function

How to use the function:

The function contains 3 arguments, values between 0 and 255 for each individual Red, Green, or Blue value.

RGB from Long

Convert from long to RGB

To convert from RGB to the long color code, use the following UDF.

Function GetRGBFromLong(longColor As Long, RGB As String) As Integer

Select Case RGB

    Case "R"
        GetRGBFromLong = (longColor Mod 256)

    Case "G"
        GetRGBFromLong = (longColor  256) Mod 256

    Case "B"
        GetRGBFromLong = (longColor  65536) Mod 256

End Select

End Function

How to use the function:

The function contains 2 arguments;

  1. the long code
  2. the letter R, G, or B, depending on which color we want to return.

Long from RGB

Convert from long to hex

The following UDF provides the hex code based on the long color code.

Function GetHexFromLong(longColor As Long) As String

Dim R As String
Dim G As String
Dim B As String

R = Format(Application.WorksheetFunction.Dec2Hex(longColor Mod 256), "00")
G = Format(Application.WorksheetFunction.Dec2Hex((longColor  256) Mod 256), "00")
B = Format(Application.WorksheetFunction.Dec2Hex((longColor  65536) Mod 256), "00")

GetHexFromLong = "#" & R & G & B

End Function

How to use the function:

The function has only one argument, which is the long color code.

Hex from Long

Convert from hex to long

The UDF below converts the hex code into the long color code.

Function GetLongFromHex(hexColor As String) As Long

Dim R As String
Dim G As String
Dim B As String

hexColor = VBA.Replace(hexColor, "#", "")
hexColor = VBA.Right$("000000" & hexColor, 6)

R = Left(hexColor, 2)
G = Mid(hexColor, 3, 2)
B = Right(hexColor, 2)

GetLongFromHex = Application.WorksheetFunction.Hex2Dec(B & G & R)

End Function

How to use the function:

The function has only one argument, which is the hex code.

Long from Hex

Convert from RGB to HSL

The UDF below will return the degree of Hue, % of Saturation, or % of Luminance based on the RGB color codes.

Function GetHSLFromRGB(Red As Integer, Green As Integer, Blue As Integer, _
    HSL As String)

Dim RedPct As Double
Dim GreenPct As Double
Dim BluePct As Double
Dim MinRGB As Double
Dim MaxRGB As Double
Dim H As Double
Dim S As Double
Dim L As Double

RedPct = Red / 255
GreenPct = Green / 255
BluePct = Blue / 255

MinRGB = Application.WorksheetFunction.Min(RedPct, GreenPct, BluePct)
MaxRGB = Application.WorksheetFunction.Max(RedPct, GreenPct, BluePct)

L = (MinRGB + MaxRGB) / 2

If MinRGB = MaxRGB Then
    S = 0
ElseIf L < 0.5 Then
    S = (MaxRGB - MinRGB) / (MaxRGB + MinRGB)
Else
    S = (MaxRGB - MinRGB) / (2 - MaxRGB - MinRGB)
End If


If S = 0 Then
    H = 0
ElseIf RedPct >= Application.WorksheetFunction.Max(GreenPct, BluePct) Then
    H = (GreenPct - BluePct) / (MaxRGB - MinRGB)
ElseIf GreenPct >= Application.WorksheetFunction.Max(RedPct, BluePct) Then
    H = 2 + (BluePct - RedPct) / (MaxRGB - MinRGB)
Else
    H = 4 + (RedPct - GreenPct) / (MaxRGB - MinRGB)
End If

H = H * 60

If H < 0 Then H = H + 360

Select Case HSL

    Case "H"
        GetHSLFromRGB = H

    Case "S"
        GetHSLFromRGB = S

    Case "L"
        GetHSLFromRGB = L

End Select

End Function

How to use the function:

The function contains 4 arguments. The R, G and B values, then the letter H, S, or L, depending on the value to be returned by the function.

HSL from RGB

The calculation for converting to HSL is based on the calculation from here: http://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/

Convert from HSL to RGB

The following UDF calculates the RGB values based on the degree of Hue, % of Saturation and % of Luminance

Function GetRGBFromHSL(Hue As Double, Saturation As Double, Luminance As Double, RGB As String)

Dim R As Double
Dim G As Double
Dim B As Double
Dim temp1 As Double
Dim temp2 As Double
Dim tempR As Double
Dim tempG As Double
Dim tempB As Double

If Saturation = 0 Then

    R = Luminance * 255
    G = Luminance * 255
    B = Luminance * 255

GoTo ReturnValue

End If

If Luminance < 0.5 Then
    temp1 = Luminance * (1 + Saturation)
Else
    temp1 = Luminance + Saturation - Luminance * Saturation
End If

temp2 = 2 * Luminance - temp1

Hue = Hue / 360

tempR = Hue + 0.333
tempG = Hue
tempB = Hue - 0.333

If tempR < 0 Then tempR = tempR + 1
If tempR > 1 Then tempR = tempR - 1
If tempG < 0 Then tempG = tempG + 1
If tempG > 1 Then tempG = tempG - 1
If tempB < 0 Then tempB = tempB + 1
If tempB > 1 Then tempB = tempB - 1

If 6 * tempR < 1 Then
    R = temp2 + (temp1 - temp2) * 6 * tempR
Else
    If 2 * tempR < 1 Then
        R = temp1
    Else
        If 3 * tempR < 2 Then
            R = temp2 + (temp1 - temp2) * (0.666 - tempR) * 6
        Else
            R = temp2
        End If
    End If
End If

If 6 * tempG < 1 Then
    G = temp2 + (temp1 - temp2) * 6 * tempG
Else
    If 2 * tempG < 1 Then
        G = temp1
    Else
        If 3 * tempG < 2 Then
            G = temp2 + (temp1 - temp2) * (0.666 - tempG) * 6
        Else
            G = temp2
        End If
    End If
End If


If 6 * tempB < 1 Then
    B = temp2 + (temp1 - temp2) * 6 * tempB
Else
    If 2 * tempB < 1 Then
        B = temp1
    Else
        If 3 * tempB < 2 Then
            B = temp2 + (temp1 - temp2) * (0.666 - tempB) * 6
        Else
            B = temp2
        End If
    End If
End If

R = R * 255
G = G * 255
B = B * 255


ReturnValue:
Select Case RGB

    Case "R"
        GetRGBFromHSL = Round(R, 0)

    Case "G"
        GetRGBFromHSL = Round(G, 0)

    Case "B"
        GetRGBFromHSL = Round(B, 0)

End Select

End Function

How to use the function:

The function contains 4 arguments. The Hue degree, Saturation %, and Luminance %, plus the letter R, G or B depending on the value to be returned

RGB from HSL

The calculation for converting from HSL is based on the calculation from here: http://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/

Convert from RGB to CMYK

The following UDF provides the % value for Cyan, Magenta, Yellow, or Black based on the RGB color codes.

Function GetCMYKFromRGB(Red As Integer, Green As Integer, Blue As Integer, CMYK As String) As Double

Dim K As Double
Dim RedPct As Double
Dim GreenPct As Double
Dim BluePct As Double
Dim MaxRGB As Double

RedPct = Red / 255
GreenPct = Green / 255
BluePct = Blue / 255
MaxRGB = Application.WorksheetFunction.Max(RedPct, GreenPct, BluePct)

If MaxRGB = 0 And CMYK <> "K" Then
    GetCMYKFromRGB = 0
    Exit Function
End If


K = 1 - MaxRGB

Select Case CMYK

    Case "C"
        GetCMYKFromRGB = (1 - RedPct - K) / (1 - K)

    Case "M"
        GetCMYKFromRGB = (1 - GreenPct - K) / (1 - K)

    Case "Y"
        GetCMYKFromRGB = (1 - BluePct - K) / (1 - K)

    Case "K"
        GetCMYKFromRGB = K

End Select

End Function

How to use the function:

The function requires 4 arguments. The R, G and B values, along with the letter C, M, Y or K, depending on the value to be returned.

CMYK from RGB

The calculation for converting to CMYK is based on the calculation from here: https://www.easycalculation.com/colorconverter/cmyk-rgb-color-convertor.php

Convert from CMYK to RGB

To get the C, M, Y, or K percentages from RGB use the UDF below.

Function GetRGBFromCMYK(C As Double, M As Double, Y As Double, K As Double, RGB As String) As Integer

Select Case RGB

    Case "R"
        GetRGBFromCMYK = 255 * (1 - K) * (1 - C)

    Case "G"
        GetRGBFromCMYK = 255 * (1 - K) * (1 - M)

    Case "B"
        GetRGBFromCMYK = 255 * (1 - K) * (1 - Y)

End Select

End Function

How to use the function:

The function requires 5 arguments. The Cyan, Magenta, Yellow and Black percentages, plus the letter R, G or B, depending on the value to be returned.

RGB from CMYK

The calculation for converting from CMYK is based on the calculation from here: https://stackoverflow.com/questions/10690125/coloring-cells-in-excel-with-cmyk-cell-values

Convert from RGB to HSV

The UDF below will return the degree of Hue, % of Saturation, or % of Value based on the RGB color codes.

Function GetHSVFromRGB(Red As Integer, Green As Integer, Blue As Integer, HSV As String)

Dim RedPct As Double
Dim GreenPct As Double
Dim BluePct As Double
Dim MinRGB As Double
Dim MaxRGB As Double
Dim H As Double
Dim S As Double
Dim V As Double

RedPct = Red / 255
GreenPct = Green / 255
BluePct = Blue / 255

MinRGB = Application.WorksheetFunction.Min(RedPct, GreenPct, BluePct)
MaxRGB = Application.WorksheetFunction.Max(RedPct, GreenPct, BluePct)

V = MaxRGB

If MaxRGB = 0 Then
    S = 0
Else
    S = (MaxRGB - MinRGB) / MaxRGB
End If


If S = 0 Then
    H = 0
ElseIf RedPct >= Application.WorksheetFunction.Max(GreenPct, BluePct) Then
    H = (GreenPct - BluePct) / (MaxRGB - MinRGB)
ElseIf GreenPct >= Application.WorksheetFunction.Max(RedPct, BluePct) Then
    H = 2 + (BluePct - RedPct) / (MaxRGB - MinRGB)
Else
    H = 4 + (RedPct - GreenPct) / (MaxRGB - MinRGB)
End If

H = H * 60

If H < 0 Then H = H + 360


Select Case HSV

    Case "H"
        GetHSVFromRGB = H
    
    Case "S"
        GetHSVFromRGB = S
    
    Case "V"
        GetHSVFromRGB = V

End Select

End Function

The calculation for converting to HSV from RGB based on the calculation from here: https://www.calculatorology.com/hsv-to-rgb-conversion/

Convert from HSV to RGB

The following UDF calculates the RGB values based on the degree of Hue, Saturation % and Value % of the HSV method.

Function GetRGBFromHSV(Hue As Double, Saturation As Double, Value As Double, RGB As String)

Dim R As Double
Dim G As Double
Dim B As Double

Dim C As Double
Dim X As Double
Dim m As Double


C = Saturation * Value
X = C * (1 - Abs((CDec(Hue / 60) - 2 * Int((Hue / 60) / 2)) - 1))
m = Value - C

If Hue >= 0 And Hue < 60 Then
    R = C
    G = X
    B = 0
ElseIf Hue >= 60 And Hue < 120 Then
    R = X
    G = C
    B = 0
ElseIf Hue >= 120 And Hue < 180 Then
    R = 0
    G = C
    B = X
ElseIf Hue >= 180 And Hue < 240 Then
    R = 0
    G = X
    B = C
ElseIf Hue >= 240 And Hue < 300 Then
    R = X
    G = 0
    B = C
Else
    R = C
    G = 0
    B = X
End If

R = (R + m) * 255
G = (G + m) * 255
B = (B + m) * 255


Select Case RGB

    Case "R"
        GetRGBFromHSV = Round(R, 0)
    
    Case "G"
        GetRGBFromHSV = Round(G, 0)
    
    Case "B"
        GetRGBFromHSV = Round(B, 0)

End Select

End Function

The calculation for converting to HSV from RGB based on the calculation from here: https://www.codespeedy.com/hsv-to-rgb-in-cpp/

Color conversion add-in

Using these conversion functions, I have created an Excel add-in that will quickly switch between the different color codes.

The add-in is included within the downloads at the top of the post. To install the add-in, follow the PDF instructions included in the download, or follow the instructions in this post.

Once installed, the EOTG menu will include an icon called Converter in the Color Codes group.

EOTG Ribbon with Color Converter Add-in

Click the button to open the tool. When entering values into any of the boxes, the other boxes will automatically display the converted codes.

Color Code Converter Add-in User Form

Conclusion

I hope this post provides you with all the color conversions that you need. If you want to convert between two methods that I have not covered above (for example, hex to HSL has not been included), convert from the source code to RGB, then from RGB to the target mode.

Related posts:

  • Calling and using the color picker with VBA
  • 5 rules for a dashboard color palette
  • Dynamic arrays and VBA user defined functions (UDFs)

Headshot Round

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).


Do you need help adapting this post to your needs?

I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise.  List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:

Понравилась статья? Поделить с друзьями:

А вот еще интересные статьи:

  • Excel получить формат ячейки в excel
  • Excel последняя буква ячейки
  • Excel получить имена столбцов
  • Excel получить текущую строку
  • Excel последняя буква в ячейке

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии