简体   繁体   中英

Color cells based on cell value

Can you help me what is wrong with my code. I get an error: Application defined or object defined error. I would like to color a cell based on a cell value. If a cell value equal to a cell-1 value the cell should be red. Error with this line: If Cells(i, 2).Value = Cells(i - 1, 3).Value Then

thank you

Sub colorcells()
ThisWorkbook.Worksheets("Sheet1").Activate
Range("A1").Select
    Dim i As Long
    lastrow = Cells(Rows.Count, "B").End(xlUp).Row
    For i = 1 To lastrow
        If Cells(i, 2).Value = Cells(i - 1, 3).Value Then
            Cells(i, 1).Interior.ColorIndex = 3
        End If
    Next i
End Sub 

Instead of using VBA, you can use conditional formatting if you are using Excel 2007 upwards, which is a lot easier to use. It provides you with dialog boxes which allow you to set rules.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM