Excel формула проверка цвета ячейки

Надстройка PLEX для Microsoft Excel 2007-2021 и Office 365

Функция CellColor

Данная функция позволяет определить внутренний числовой Excel код цвета заливки любой указанной ячейки. Это дает возможность пользователю впоследствии производить сортировку и фильтрацию ячеек по цвету, что часто бывает необходимо.

Определение кода цвета ячейки с помощью функции CellColor

Синтаксис

=CellColor(cell)

где

  • cell — ячейка, для которой нужно определить код цвета заливки

Примечания

К сожалению, поскольку Excel формально не считает смену цвета  изменением содержимого листа, то эта функция не будет пересчитываться автоматически при изменении форматирования — обновление значений этой функции происходит только при нажатии сочетания клавиш полного пересчета листа Ctrl+Alt+F9.

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

Если для ячейки не установлен цвет заливки, то код = -4142.

Если нужен RGB-код цвета, то используйте функцию RGBCellColor.

Если нужен код цвета не заливки, а шрифта, то используйте функцию CellFontColor.

Полный список всех инструментов надстройки PLEX

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

I would like to know if we can find out the Color of the CELL with the help of any inline formula (without using any macros)

I’m using Home User Office package 2010.

Lance Roberts's user avatar

Lance Roberts

22.2k32 gold badges112 silver badges129 bronze badges

asked Jun 24, 2014 at 9:07

Praveen's user avatar

2

As commented, just in case the link I posted there broke, try this:

Add a Name(any valid name) in Excel’s Name Manager under Formula tab in the Ribbon.
Then assign a formula using GET.CELL function.

=GET.CELL(63,INDIRECT("rc",FALSE))

63 stands for backcolor.
Let’s say we name it Background so in any cell with color type:

=Background

Result:
enter image description here

Notice that Cells A2, A3 and A4 returns 3, 4, and 5 respectively which equates to the cells background color index. HTH.
BTW, here’s a link on Excel’s Color Index

answered Jun 24, 2014 at 9:34

L42's user avatar

L42L42

19.3k11 gold badges43 silver badges68 bronze badges

6

Color is not data.

The Get.cell technique has flaws.

  1. It does not update as soon as the cell color changes, but only when
    the cell (or the sheet) is recalculated.
  2. It does not have sufficient numbers for the millions of colors that are available in modern Excel. See the screenshot and notice how the different intensities of yellow or purple all have the same number.

enter image description here

That does not surprise, since the Get.cell uses an old XML command, i.e. a command from the macro language Excel used before VBA was introduced. At that time, Excel colors were limited to less than 60.

Again: Color is not data.

If you want to color-code your cells, use conditional formatting based on the cell values or based on rules that can be expressed with logical formulas. The logic that leads to conditional formatting can also be used in other places to report on the data, regardless of the color value of the cell.

answered Jun 24, 2014 at 10:31

teylyn's user avatar

teylynteylyn

34.1k4 gold badges52 silver badges72 bronze badges

5

No, you can only get to the interior color of a cell by using a Macro. I am afraid. It’s really easy to do (cell.interior.color) so unless you have a requirement that restricts you from using VBA, I say go for it.

Myrddin Emrys's user avatar

answered Jun 24, 2014 at 9:13

Gaijinhunter's user avatar

GaijinhunterGaijinhunter

14.5k4 gold badges50 silver badges57 bronze badges

1

Anticipating that I already had the answer, which is that there is no built-in worksheet function that returns the background color of a cell, I decided to review this article, in case I was wrong. I was amused to notice a citation to the very same MVP article that I used in the course of my ongoing research into colors in Microsoft Excel.

While I agree that, in the purest sense, color is not data, it is meta-data, and it has uses as such. To that end, I shall attempt to develop a function that returns the color of a cell. If I succeed, I plan to put it into an add-in, so that I can use it in any workbook, where it will join a growing legion of other functions that I think Microsoft left out of the product.

Regardless, IMO, the ColorIndex property is virtually useless, since there is essentially no connection between color indexes and the colors that can be selected in the standard foreground and background color pickers. See Color Combinations: Working with Colors in Microsoft Office and the associated binary workbook, Color_Combinations Workbook.

answered Sep 18, 2015 at 20:35

David A. Gray's user avatar

2

Надо сделать условие в зависимости от цвета (шрифта, цвета текста и тп.) ячейки. . То есть должно получиться, что-то типа:
ЕСЛИ(цвет ячейки зеленый;истина;ложь)

Подскажите пожайлуста, как это делается. :)


По цвету не знаю, но можно например по формату ячейки:
=ЕСЛИ(ЯЧЕЙКА(«формат»;E4)=G;истина;ложь)
Про форматы в функции ЯЧЕЙКА есть в справке.


«G» — это вроде как что-то типа стандартного формата ячейки, такое я уже пробовала, нифига не считает :(


Dmitr68, вообще у меня получается вот такая мега-формула:
=ЕСЛИ(ЯЧЕЙКА(«формат»;RC[-25])=G;ЕСЛИ(ЕПУСТО(RC[-25]);0;(2*RC38*264*RC[-25]));ЕСЛИ(ЕПУСТО(RC[-25]);0;(2*RC38*264*RC[-25]+RC6*258)))
RC[-25] — это ячейка, которая стоит 25 ячеек назад. RC38, RC6 — это ячейки в 38м и в 6м столбце соответственно. Все находится в той же строке, в которой формула.
ЕПУСТО — оператор проверки наличия хоть чего-нибудь в ячейке.
Должно получиться так:
Если цвет ячейки отличается от стандартного, и в ней что-то написано, то выполняется условие 2*RC38*264*RC[-25]+RC6*258; если цвет не отличается, то должно выполниться 2*RC38*264*RC[-25]; если в ячейке ничего нет, то должно быть значение 0 (Умножать все на значение ячейки не получается, формала выдает неправильные результаты, там все мудрено).
То есть сначала оно должно проверять на наличие света ячеек, потом на наличие в них хоть какого-нибудь значения. В зависимости от цвета, она должна подсчитавыть разные значения. (Цвет ячеки либо стандартный, либо любой другой)

Я честно хз, где там ошибка, вроде по логике все правильно, но не считает :((



Цитата: kettary@mail.ru от 07.01.2010, 19:18
Надо сделать условие в зависимости от цвета (шрифта, цвета текста и тп.) ячейки.

Какой то «шыворот на выворот».
Если цвет ячеек меняется, то для этого, наверное, уже существуют
какие то условия. Я бы поискал другое решение проблеммы.

Может и я на что сгожусь … Если сгодился, можете меня по+благодарить+.


Цвет заливки ячейки

Jowls

Дата: Понедельник, 14.11.2022, 17:26 |
Сообщение № 1

Группа: Пользователи

Ранг: Новичок

Сообщений: 11

Добрый день,
Подскажите, пожалуйста, как узнать цифровой код цвета заливки ячейки?

Заранее благодарю.

 

Ответить

Serge_007

Дата: Понедельник, 14.11.2022, 17:35 |
Сообщение № 2

Группа: Админы

Ранг: Местный житель

Сообщений: 15888


Репутация:

2623

±

Замечаний:
±


Excel 2016

Здравствуйте

Пользовательской функцией:[vba]

Код

Function CellColour(RCell As Range) As Double
    CellColour = RCell.Interior.Color
End Function

[/vba]


ЮMoney:41001419691823 | WMR:126292472390

 

Ответить

Gustav

Дата: Понедельник, 14.11.2022, 17:51 |
Сообщение № 3

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

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

Сообщений: 2398


Репутация:

985

±

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


начинал с Excel 4.0, видел 2.1

До кучи — цвет в виде вызова функции RGB с соответствующими параметрами-цветами:
[vba]

Код

Function CellRGB(RCell As Range) As String
    Dim color As Long
    color = RCell.Interior.color
    CellRGB = «RGB(» & (color Mod 256) & «, » & ((color 256) Mod 256) & «, » & (color 65536) & «)»
End Function

[/vba]


МОИ: Ник, Tip box: 41001663842605

 

Ответить

Jowls

Дата: Вторник, 15.11.2022, 10:33 |
Сообщение № 4

Группа: Пользователи

Ранг: Новичок

Сообщений: 11

Коллеги, всем спасибо.

Но у меня, при использовании варианта:[vba]

Код

Function CellColour(RCell As Range) As Double
CellColour = RCell.Interior.Color
End Function

[/vba]Выдает синтаксическую ошибку (файл в приложении)
Никак не пойму, в чем дело.

К сообщению приложен файл:

8911575.xlsm
(15.4 Kb)

Сообщение отредактировал Serge_007Вторник, 15.11.2022, 12:44

 

Ответить

Nic70y

Дата: Вторник, 15.11.2022, 11:29 |
Сообщение № 5

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

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

Сообщений: 8132


Репутация:

1998

±

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


Excel 2010

Jowls, нельзя называть модуль именем функции,
не конечно можно, но не нужно.
переименуйте их и будет все норм


ЮMoney 41001841029809

 

Ответить

Jowls

Дата: Вторник, 15.11.2022, 11:48 |
Сообщение № 6

Группа: Пользователи

Ранг: Новичок

Сообщений: 11

Nic70y,

О, спасибо огромное!!!
Помогло!

 

Ответить

Понравилась статья? Поделить с друзьями:
  • Excel формула проверка на ошибку
  • Excel формула привязка к ячейке
  • Excel формула прибыль убыток
  • Excel формула прибавить рабочие дни
  • Excel формула прибавить один месяц