简体   繁体   中英

VBA to color row based on other column values

I am trying to color the each rows in column A based on the row color of COL B, C, D.

Say A2 color is based on colors of B2,C2,D2. If either of them has Red, then A2 should be red else A2 gets green

Please find my code below:

Option Explicit

Sub Sheet1()

Dim lastR As Long
Dim i As Long

lastR = Sheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row

For i = lastR To 2 Step -1

    If ((Sheets("Sheet1").Cells(i, "B")) Or (Sheets("Sheet1").Cells(i, "C")) Or (Sheets("Sheet1").Cells(i, "D"))) = Rows(i).Interior.Color = RGB(255, 0, 0) Then
        Rows(i).Interior.Color = RGB(0, 255, 0)
    End If

Next i

End Sub

I am getting subscript out of range, error code 9.

This is my excel screen print:

在此处输入图片说明

Try this:

Sub Sheet1()
    Dim rng As Range, cl As Range

    For Each cl In Worksheets("Sheet1").Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row)
        If cl.Offset(0, 1).Interior.Color = 255 Or cl.Offset(0, 2).Interior.Color = 255 Or cl.Offset(0, 3).Interior.Color = 255 Then
            cl.Interior.Color = 255
        End If
    Next cl
End Sub

I think the problem is in lastR = Sheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row .

Sheets("Sheet1").Cells(Rows.Count, "A") will find the last cell and then the .End(xlUp) will bring the selection again to the first row.

When you say then For i = lastR To 2 Step -1 you probably want to go from the first row to the second with a -1 step. Which is impossible.

Change your cell references to look like this (example for column B):

Cells(i, 2)

If you were to use Range() , you could do it in the style you had tried, but you would need to concatenate the values into the "A1" style cell references, like this:

Range("B" & i)

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