Formula for excel cell color

You can use a formula in conjunction with an Event Macro. Pick a cell, say B2 and enter the formula:

=IF(A1>10,"black","green")

Then format B2 Custom ;;;
This will hide the displayed text.
Then place the following event macro in the worksheet code area:

Private Sub Worksheet_Calculate()
Application.EnableEvents = False
    With Range("B2")
        If .Value = "green" Then
            .Interior.Color = RGB(0, 255, 0)
        Else
            .Interior.Color = RGB(0, 0, 0)
        End If
    End With
Application.EnableEvents = True
End Sub

The macro will run every time the worksheet is re-calculated. It will exame the text in B2 (even though the text is not visible) and adjust the backgound color accordingly.

Because it is worksheet code, it is very easy to install and automatic to use:

  1. right-click the tab name near the bottom of the Excel window
  2. select View Code — this brings up a VBE window
  3. paste the stuff in and close the VBE window

If you have any concerns, first try it on a trial worksheet.

If you save the workbook, the macro will be saved with it.
If you are using a version of Excel later then 2003, you must save
the file as .xlsm rather than .xlsx

To remove the macro:

  1. bring up the VBE windows as above
  2. clear the code out
  3. close the VBE window

To learn more about macros in general, see:

http://www.mvps.org/dmcritchie/excel/getstarted.htm

and

http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

To learn more about Event Macros (worksheet code), see:

http://www.mvps.org/dmcritchie/excel/event.htm

Macros must be enabled for this to work!

@Radish_G 

You may use the following User Defined Function to get the Color Index or RGB value of the cell color.

Place the following function on a Standard Module like Module1…

Function getColor(Rng As Range, ByVal ColorFormat As String) As Variant
    Dim ColorValue As Variant
    ColorValue = Cells(Rng.Row, Rng.Column).Interior.Color
    Select Case LCase(ColorFormat)
        Case "index"
            getColor = Rng.Interior.ColorIndex
        Case "rgb"
            getColor = (ColorValue Mod 256) & ", " & ((ColorValue  256) Mod 256) & ", " & (ColorValue  65536)
        Case Else
            getColor = "Only use 'Index' or 'RGB' as second argument!"
    End Select
End Function

And then assuming you want to check the color index or the RGB of the cell A2, try the UDF on the worksheet like below…

To get Color Index:

=getcolor(A2,"index")

To get RGB:

=getcolor(A2,"rgb")

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

Функция CellColor

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

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

Синтаксис

=CellColor(cell)

где

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

Примечания

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

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

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

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

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

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

Let’s say that one of our tasks is to entering of the information about: did the ordering to a customer in the current month. Then on the basis of the information you need to select the cell in color according to the condition: which from customers have not made any orders for the past 3 months. For these customers you will need to re-send the offer.

Of course it’s the task for Excel. The program should automatically find such counterparties and, accordingly, to color ones. For these conditions we will use to the conditional formatting.



The filling cells with dates automatically

At first, you need to prepare to the structure for filling the register. First of all, let’s consider to the ready example of the automated register, which is depicted in the picture below. Today date 07.07.2018:

Today.

The user to need only to specify, if the customer have made an order in the current month, in the corresponding cell you should enter the text value of «order». The main condition for the allocation: if for 3 months the contractor did not make any order, his number is automatically highlighted in red.

Presented this decision should automate some work processes and to simplify to the visual data analysis.

The automatic filling of the cells with the relevant dates

At first, for the register with numbers of customers we will create to the column headers with green and up to date for months that will automatically display to the periods of time. To do this, in the cell B1 you need to enter the following formula:

DATE.

How does the formula work for automatically generating of the outgoing months?

In the picture, the formula returns the period of time passing since the date of writing this article: 17.09.2017. In the first argument in the function DATE is the nested formula that always returns the current year to today’s date thanks to the functions: YEAR and TODAY. In the second argument is the month number (-1). The negative number means that we are interested in what it was a month last time. The example of the conditions for the second argument with the value:

  • 1 means the first month (January) in the year that is specified in the first argument;
  • 0 – it is 1 month ago;
  • -1 – there is 2 months ago from the beginning of the current year (i.e. 01.10.2016).

The last argument-is the day number of the month, which is specified in the second argument. As a result, the DATE function collects all parameters into a single value and the formula returns to the corresponding date.

Next, go to the cell C1 and type the following formula:

MONTH.

As you can see now the DATE function uses the value from the cell B1 and increases to the month number by 1 in relation to the previous cell. As the result is the 1 – the number of the following month.

Now you need to copy this formula from the cell C1 in the rest of the column headings in the range D1:AY1.

To highlight to the cell range B1:AY1 and select to the tool: «HOME»-«Cells»-«Format Cells» or just to press CTRL+1. In the dialog box that appears, in the tab «Number» in the section «Category» you need to select the option «Custom». In the «Type:» to enter the value: MMM. YY (required the letters in upper register). Because of this, we will get to the cropped display of the date values in the headers of the register, what simplifies to the visual analysis and make it more comfortable due to better readability.

Format Cells.

Please note! At the onset of the month of January (D1), the formula automatically changes in the date to the year in the next one.



How to select the column by color in Excel under the terms

Now you need to highlight to the cell by color which respect of the current month. Because of this, we can easily find the column in which you need to enter the actual data for this month. To do this:

  1. To select the range of the cells B2:AY15 and select the tool: «HOME» -«Styles» -«Conditional Formatting»-«New Rule». And in the appeared window «New Formatting Rule» you need to select the option: «Use a formula to determine which cells to format»
  2. Conditional Formatting.

  3. In the input field to enter the formula:
  4. input field.

  5. Click «Format» and indicate on the tab «Fill» in what color (for example green) will be the selected cells of the current month. Then on all Windows for confirmation to click «OK».

Format.

The column under the appropriate heading of the register is automatically highlighted in green accordingly to our terms and conditions:

register is automatically.

How does the formula highlight of the column color on a condition work?

Due to the fact that before the creation of the conditional formatting rule we have covered all the table data for inputting data of register, the formatting will be active for each cell in the range B2:AY15. The mixed reference in the formula B$1 (absolute address only for rows, but for columns it is relative) determines that the formula will always to refer to the first row of each column.

Automatic highlighting of the column in the condition of the current month

The main condition for the fill by color of the cells: if the range B1:AY1 is the same date that the first day of the current month, then the cells in a column change its colors by specified in conditional formatting.

Please note! In this formula, for the last argument of the function DATE is shown 1, in the same way as for formulas in determining the dates for the column headings of the register.

In our case, is the green filling of the cells. If we open our register in next month, that it has the corresponding column is highlighted in green regardless of the current day.

The table is formatted, now we are filling it with the text value of the «order» in a mixed order of clients for current and past months.

How to highlight the cells in red color according to the condition

Now we need to highlight in red to the cells with the numbers of clients who for 3 months have not made any order. To do this:

  1. Select the range of the cells A2:A15 (that is, the list of the customer numbers) and select to the tool: «HOME»-«Styles»-«Conditional formatting»-«Create rule». And in the window that appeared «Create a formatting rule» to select the option: «Use the formula for determining which cells to format».
  2. This time in the input box to enter the formula:
  3. COUNTIF.

  4. To click «Format» and specify the red color on the tab «Fill». Then on all Windows click «OK».
  5. Fill the cells with the text value of «order» as in the picture and look at the result:

result.

The numbers of customers are highlighted in red, if in the row has no have the value «order» in the last three cells for the current month (inclusively).

The analysis of the formula for the highlighting of cells according to the condition

Firstly, we will do by the middle part of our formula. The SHIFT function returns a range reference shifted relative to the basic range of the certain number of rows and columns. The returned reference can be a single cell or a range of cells. Optionally, you can define to the number of returned rows and columns. In our example, the function returns the reference to the cell range for the last 3 months.

The important part for our terms of highlighting in color – is belong to the first argument of the SHIFT function. It determines from which month to start the offset. In this example, there is the cell D2, that is, the beginning of the year – January. Of course for the rest of the cells in the column the row number for the base of the cell will correspond to the line number in what it is located. The following 2 arguments of the SHIFT function to determine how many rows and columns should be done offset. Since the calculations for each customer will carry in the same line, the offset value for the rows we specified is -0.

At the same time for the calculating the value of the third argument (the offset by the columns) we use to the nested formula MONTH(TODAY()), which in accordance with the terms returns to the number of the current month in the current year. From the calculated formula of the month as a number subtract the number 4, that is, in cases November we get the offset by 8 columns. And, for example, for June – there are on 2 columns only.

The last two arguments for the SHIFT function, determine the height (in the number of rows) and width (in the number of columns) of the returned range. In our example, there is the area of the cell with height on 1 row and with width on 4 columns. This range covers to the columns of 3 previous months and the current month.

The first function in the COUNTIF formula checks the condition: how many times in the returned range using the SHIFT function, we can found to the text value «order». If the function returns the value of 0, it means from the client with this number for 3 months there was not any order. And in accordance with our terms and conditions, the cell with number of this client is shown in red fill color.

If we want to register to data for customers, Excel is ideally suited for this purpose. You can easily record in the appropriate categories to the number of ordered goods, as well as the date of implementation of transaction. The problem gradually starts with arising of the data growth.

Download example automatic highlight cells by color.

If so many of them that we need to spend a few minutes looking for a specific position of the register and analysis of the information entered. In this case, it is necessary to add in the table to the register of mechanisms to automate some workflows of the user. And so we did.

There are several ways to color format cells in Excel, but not all of them accomplish the same thing. If you want to fill a cell with color based on a condition, you will need to use the Conditional Formatting feature.

Fill a cell with color based on a condition

Before learning to conditionally format cells with color, here is how you can add color to any cell in Excel. 

Cell static format for colors

You can change the color of cells by going into the formatting of the cell and then go into the Fill section and then select the intended color to fill the cell.

In the above example, the color of cell E3 has been changed from No Fill to Blue color, and notice that the value in cell E3 is 6 and if we change the value in this cell from 6 to any other value the cell color will not change and it will always remain blue. What does this mean?

This means that cell color is independent of cell value, so no matter what value will be in E3 the cell color will always be blue. We can refer to this as static formatting of the cell E3.

Conditional formatting cell color based on cell value

Now, what if we want to change the cell color based on cell value? Suppose we want the color of cell E3 to change with the change of the value in it. Say, we want to color code the cell E3 as follows:

  • 0-10 : We want the cell color to be Blue
  • 11-20 : We want the cell color to be Red
  • 21-30 : We want the cell color to be Yellow
  • Any other value or Blank : No color or No Fill.

We can achieve this with the help of Conditional Formatting. On the Home tab, in the Style subgroup, click on Conditional FormattingNew Rule.

Note: Make sure the cell on which you want to apply conditional formatting is selected

Then select “Format only cells that contain,” then in the first drop down select “Cell Value” and in the second drop-down select “between” :

Then, on the first box, enter 0 and in the second box, enter 10, then click on the Format button and go to Fill Tab, select the blue color, click Ok and again click Ok. Now enter a value between 0 and 10 in cell E3 and you will see that cell color changes to blue and if there is any other value or no value then cell color revert to transparent.

Repeat the same process for 11-20 and 21-30 and you’ll see that number changes as per the value of the cell.

Conditional formatting with text

Similarly, we can do the same process for text values as well instead of numerical values by using the “Specific Text” in the first drop down and in the second drop-down select either of 4 values containing, not containing, beginning with, ending with and then enter the specific text in the text box.

For Example:

First, select the cell on which you want to apply conditional format, here we need to select cell B1. On the home tab, in the Styles subgroup, click on Conditional Formatting→New Rule.

Now select Format only cells that contain the option, then in the first drop down select “Specific Text” and in the second drop-down select either of the 4 options: containing, not containing, beginning with, ending with. In the example below, we use beginning with “J” and then select Format button to select Blue as the fill color.

Conditional format based on another cell value

In the example above, we are changing the cell color based on that cell value only, we can also change the cell color based on other cells value as well. Suppose we want to change the color of cell E3 based on the value in D3, to do that we have to use a formula in conditional formatting.

Now suppose if we want to change cell E3 color to blue if the D3 value is greater than 3 and to green if the D3 value is greater than 5 and to red, if D3’s value is greater than 10, we can do that with the conditional format using a formula.

Again follow the same procedure.

First, select the cell on which you want to apply conditional format, here we need to select cell E3. On the home tab, in the Styles subgroup, click on Conditional Formatting→New Rule.

Now select Use a formula to determine which cells to format option, and in the box type the formula: D3>5; then select Format button to select green as the fill color.

Keep in mind that we are changing the format of cell E3 based on cell D3 value, note that the cursor now is pointing at E3, which is the cell we use to set conditional format. The formula “=D3>5” means if D3 is greater than 5 then the value of E3 will change to green. Click ok and see the color of cell E3 changes to green as D3 right now contains 6.

Now let’s apply the conditional formatting to E3 if D3 is greater than 3. This means if D3>3 then cell color should become “Blue” and if D3>5 then cell color should remain green as we did it in the previous step.

Now, if you follow the above steps as we did for Green color, you will see that even if the cell value is 6, it is showing blue color and not green, because it takes the latest conditional formatting we set for that cell, and as 6 is also greater than 3 hence it is showing blue color but it should show green color.

So, we have to arrange the rules we have applied for any particular cells, we can do that by going into Manage Rules option of conditional formatting.

You can see all the rules applied to that cell and then we can arrange the rules or set their priority by using the arrow buttons. A number greater than 5 will also be greater than 3, hence greater than 5 rule will take higher priority and we can move it upward using the arrow buttons.

Now when you enter 6 in D3, the cell color of E3 will become green and when you enter 4, the cell color will become blue.

If you are tired of reading too many articles without finding your answer or need a real Expert to help you save hours of struggle, click on this link to enter your problem and get connected to a qualified Excel expert in a few seconds. You can share your file and an expert will create a solution for you on the spot during a 1:1 live chat session. Each session last less than 1 hour and the first session is free.

Are you still looking for help with Conditional Formatting? View our comprehensive round-up of Conditional Formatting tutorials here.

Понравилась статья? Поделить с друзьями:
  • Formula for change in excel
  • Forms of the word abuse
  • Formula for cell value in excel
  • Forms of the word abstract
  • Formula for cell number excel