VBA to colour cells if they are equal to or greater than another worksheet cell value

zaincmt

New Member
Joined
Jun 8, 2015
Messages
14
Hi All,

Please could you help me. I am trying to loop through the rows in my worksheet and then if the cells in a column match a value in another worksheets cell then I need it to change to colour of the cell.

My Main table has about 50 rows and the headers start in row 2. There are 23 Columns (upto column "W")

So far I have made this code which almost works. However it doesn't get to the end row and misses the bottom 10. (There are about 50 rows). Once I get this code to work I need to copy it and do the same for 5 other columns in the same table but the cell values will be from various worksheets in the same Workbook.

Code:
Private Sub Worksheet_Activate()
Dim MyWorkbook As Workbook
Dim MySummary As Worksheet
Dim MyData As Worksheet
Dim cell As Range
Dim Rng As Range
Dim lastRow1 As Long
Dim color_green As Long
Dim color_red As Long
Dim color_blue As Long

Set MyWorkbook = ActiveWorkbook
Set MySummary = MyWorkbook.Sheets("Main")
Set MyData = MyWorkbook.Sheets("DataSheet1")

lastRow1 = MySummary.UsedRange.Rows.Count 'This is a better function to get the last used row (though there are disagreements on this)

color_green = 10
    ActiveWorkbook.Colors(color_green) = RGB(155, 187, 89)
color_red = 9
    ActiveWorkbook.Colors(color_red) = RGB(192, 80, 77)
color_blue = 8
    ActiveWorkbook.Colors(color_blue) = RGB(141, 180, 226)

With MySummary
    Set Rng = .Range(.Range("A3"), .Range("A" & lastRow1).End(xlUp))
End With

For Each cell In Rng
    If cell.Offset(, 3).Value > MyData.Range("F3").Value Then
        cell.Offset(, 3).Interior.ColorIndex = 10
    Else
        cell.Offset(, 3).Interior.ColorIndex = 9
    End If
Next

End Sub
I would appreciate any assistance. Thank you.
GS
 
Last edited:

Some videos you may like

Excel Facts

Show numbers in thousands?
Use a custom number format of #,##0,K. Each comma after the final 0 will divide the displayed number by another thousand

Eric W

MrExcel MVP
Joined
Aug 18, 2015
Messages
9,809
Are there any empty cells in your range? The xlUp function only works properly if there are no gaps. You can probably just use:

Set Rng = .Range(.Range("A3"), .Range("A" & lastRow1))

to set the range.

Also, that routine looks fairly simple. I'd bet that you could use Conditional Formatting instead.
 

Watch MrExcel Video

Forum statistics

Threads
1,100,191
Messages
5,473,041
Members
406,843
Latest member
David_Welland

This Week's Hot Topics

Top