Having trouble with IF statement.

Wamhoi

New Member
Joined
Mar 4, 2011
Messages
48
Hi All,

I keep getting an error with the following If statement

Code:
Dim lastline As Long
lastline = Cells(Rows.Count, 2).End(xlUp).Row
For i = 2 To lastline

        If Cells(i, 1).Value = "R" Then _
            Cells(i, 1).Select
            Selection.Interior.Color = 192
        ElseIf Cells(i, 1).Value = "A" Then _
            Cells(i, 1).Select
            Selection.Interior.Color = 49407
        Else: Cells(i, 1).Select
            Selection.Interior.Color = 5296274
        End If
Next i
 

Excel Facts

When they said...
When they said you are going to "Excel at life", they meant you "will be doing Excel your whole life".
Why don't you just use Conditional Formatting?

Also, you don't need to Select or Activate cells in order to work with them, you can work with cells/ranges directly. I would also use Select Case instead of that structure:

Code:
Sub test()
Dim lastline As Long, lngColor As Long
lastline = Cells(Rows.Count, 2).End(xlUp).Row
For i = 2 To lastline
    Select Case UCase(Cells(i, 1))
        Case "R": lngColor = 192
        Case "A": lngColor = 49407
        Case Else: lngColor = 5296274
    End Select
    Cells(i, 1).Interior.Color = lngColor
Next i
End Sub
 
Upvote 0
remove the underscore
Code:
If Cells(i, 1).Value = "R" Then
            Cells(i, 1).Interior.Color = 192
        ElseIf Cells(i, 1).Value = "A" Then
            Cells(i, 1).Interior.Color = 49407
        Else: Cells(i, 1).Interior.Color = 5296274
        End If
<!-- / message -->
 
Upvote 0

Forum statistics

Threads
1,224,564
Messages
6,179,547
Members
452,925
Latest member
duyvmex

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top