Hosey93
Hosey93

Reputation: 47

If statement based on numerical value where cell can contain text

I have written VBA code to color a cell red based on a different cell.

I cannot get it to work if the cell has text instead of a numerical value.

Sub RoutingCheck()

    Dim I As Long, r1 As Range, r2 As Range

    For I = 2 To 456

        Set r1 = Range("A" & I)

        Set r2 = Range("B" & I)

        If r1.Value = 94 And r2.Value = -99 Then r2.Interior.Color = vbRed

    Next I

    'Error

    End Sub

Upvotes: 0

Views: 66

Answers (1)

David Zemens
David Zemens

Reputation: 53663

You need to check for numeric values before you do the comparison, otherwise a mismatch error will raise:

If IsNumeric(r1.Value) And IsNumeric(r2.Value) Then
    If r1.Value = 94 And r2.Value = -99 Then r2.Interior.Color = vbRed
End If

Upvotes: 2

Related Questions