Search code examples
excelexcel-2007vba

Combine two Worksheet_Change Subs


I need two actions to take place on one sheet in my workbook. Both are based on a change event, but do not know how to make them both work. Below is the codes that I have:

Private Sub Worksheet_Change(ByVal Target As Range)

Dim r As Range
Set r = Target.EntireRow

    If Target.row = 1 Then Exit Sub ' Don't change header color

    If r.Cells(1, "AD").Value <> "" Then
        r.Font.Color = RGB(0, 176, 80)
    Else
        r.Font.ColorIndex = 1
    End If
End Sub

And this one:

Private Sub Worksheet_Change(ByVal Target As Range)

Dim r As Range
Set r = Target.EntireRow

    If Target.row = 1 Then Exit Sub ' Don't change header color

    If r.Cells(1, "E").Value = "6" Then
        r.Font.Color = RGB(255, 0, 0)
    Else
        r.Font.ColorIndex = 1
    End If
End Sub

To help determine the best course of action, here is what the end results must be:

For any row that has a date entered into cell AD, the text color for the entire row should change to green. However, if cell E of any row contains a 6 (this is a number formatted as text), then the text in that row should be red.

I am sure that I am over thinking this. All suggestions are appreciated.


Solution

  • Use an And in your first If statement, and add an ElseIf statements.

    I am not exactly sure what you want to take precedence if both a date and 6 exist or if there is one without the other, but you can easily adjust the If Then ElseIf block below to sort out your needs.

    If r.Cells(1, "AD").Value <> "" And r.cells(1,"E").Value = "6" Then
        r.Font.Color = RGB(255, 0, 0)
    ElseIf r.Cells(1,"AD").Value <> "" Then 
        r.Font.Color = RGB(0, 176, 80)
    Else
        r.Font.ColorIndex = 1
    End If