In this article, you will learn how to get color of the cell using VBA code.
We need to follow the below steps to launch VB editor.
Click on Developer tab
From Code group, select Visual Basic
Click on Insert, and then Module
This will create a new module.
Enter the following code in the Module
Function ColorIndex(CellColor As Range)
ColorIndex = CellColor.Interior.ColorIndex
End Function
To get the color of the below cells, refer below snapshot
In cell B2, enter the formula as =ColorIndex(A2) & then copy down the formula in below cells.
Let us take one more example:
To know how many times a particular color has repeated (count by color), refer below snapshot
We can use COUNTIF function along with newly created UDFColorIndex function.
COUNTIF: Counts the number of cells within a range that meets the condition.
Syntax: =COUNTIF(range,criteria)
range: It refers to the range of selected cells from which the criteria will check the number of items that have found.
criteria: The criteria define which cells to count.
In cell D2, the formula would be =COUNTIF($B$2:$B$9,ColorIndex(D2))
By copying the formula in cell E2, we will get the count by colors.
This is how we can get the color of any cell.
The applications/code on this site are distributed as is and without warranties or liability. In no event shall the owner of the copyrights, or the authors of the applications/code be liable for any loss of profit, any problems or any damage resulting from the use or evaluation of the applications/code.
Thank you, this is great.
Is there any way to make the formula volatile (update as soon as the cell value changes)?
Yes, you can use VBA sheet_change event. Here is the link.
https://www.exceltip.com/tips/using-worksheet-change-event-to-run-macro-when-any-change-is-made.html
Thank you very much!
Hi ,
My issues is like , If cell A2 color is Green , i want to replicate the same color in another cell A8.. not color value.
for example.
A2 cell color = green , then A8 color is also green.
if i change A2 color into red = A8 also turn into red.
Kinldy help into this.
Thanks in advance.
I had some success using a form of Range().Interior.Color equal to whatever reference cell has the color you want copied. Hope this helps some, I am still trying to adjust things to work correctly in Excel 2010, will update if I figure anything else out
Did you manage to change cell color based on ref. cell?