You are on page 1of 2

Color cells with the same value in a Range, worksheet or all worksheets

This example color all cells in the range Sheets("Sheet1").Range("B1:D100") with


"ron". See the comments in the code if you want to use all cells on the worksheet.
I use the color index in this example to give all cells with "ron" the color 3
(normal this is red)

See this site for all the 56 index numbers


http://dmcritchie.mvps.org/excel/colors.htm

Tip: For changing the Font color see the example lines below the macros.

Sub Color_cells_In_Range_Or_Sheet()
Dim FirstAddress As String
Dim MySearch As Variant
Dim myColor As Variant
Dim Rng As Range
Dim I As Long

'Fill in the search Value and color Index


MySearch = Array("ron")
myColor = Array("3")

'You can also use more values in the Array


'MySearch = Array("ron", "jelle", "judith")
'myColor = Array("3", "6", "10")

'Fill in the Search range, for the whole sheet use


'you can use Sheets("Sheet1").Cells
With Sheets("Sheet1").Range("B1:D100")

'Change the fill color to "no fill" in all cells


.Interior.ColorIndex = xlColorIndexNone

For I = LBound(MySearch) To UBound(MySearch)

'If you want to find a part of the rng.value then use xlPart
'if you use LookIn:=xlValues it will also work with a
'formula cell that evaluates to MySearch(I)
Set Rng = .Find(What:=MySearch(I), _
After:=.Cells(.Cells.Count), _
LookIn:=xlFormulas, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)

If Not Rng Is Nothing Then


FirstAddress = Rng.Address
Do
Rng.Interior.ColorIndex = myColor(I)
Set Rng = .FindNext(Rng)
Loop While Not Rng Is Nothing And Rng.Address <> FirstAddress
End If
Next I
End With
End Sub
Example for all worksheets in the workbook
Sub Color_cells_In_All_Sheets()
Dim FirstAddress As String
Dim MySearch As Variant
Dim myColor As Variant
Dim Rng As Range
Dim I As Long
Dim sh As Worksheet

'Fill in the search Value and color Index


MySearch = Array("ron")
myColor = Array("3")

'You can also use more values in the Array


'MySearch = Array("ron", "jelle", "judith")
'myColor = Array("3", "6", "10")

For Each sh In ActiveWorkbook.Worksheets

'Fill in the Search range, for a range on each sheet


'you can also use sh.Range("B1:D100")
With sh.Cells

'Change the fill color to "no fill" in all cells


.Interior.ColorIndex = xlColorIndexNone

For I = LBound(MySearch) To UBound(MySearch)

'If you want to find a part of the rng.value then use xlPart
'if you use LookIn:=xlValues it will also work with a
'formula cell that evaluates to MySearch(I)
Set Rng = .Find(What:=MySearch(I), _
After:=.Cells(.Cells.Count), _
LookIn:=xlFormulas, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)

If Not Rng Is Nothing Then


FirstAddress = Rng.Address
Do
Rng.Interior.ColorIndex = myColor(I)
Set Rng = .FindNext(Rng)
Loop While Not Rng Is Nothing And Rng.Address <> FirstAddress
End If
Next I
End With
Next sh
End Sub

You might also like