Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to loop through 5 cells, Q5 - U5.

With each cell I want to check if the value is equal to "Y", and if yes, highlight the cell to make it green.

How may I do so? Can't seem to figure it out.

For Each c In Range("Q5:U5").Cells
c.Select
If c.Value = Y Then
With Selection.Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .Color = 5287936
    .TintAndShade = 0
    .PatternTintAndShade = 0
End With
End If
Next
share|improve this question
add comment

3 Answers

up vote 5 down vote accepted

You should try to avoid selecting/activating ranges: in 99% of cases there is no need (although the macro recorder always suggests otherwise)

For Each c In ActiveSheet.Range("Q5:U5").Cells
    If c.Value = "Y" Then
    With c.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 5287936
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
    End If
Next
share|improve this answer
add comment

In your code, Y appears to be an undefined variable. To check for the value, put it in double quotes:

If c.Value = "Y" Then

share|improve this answer
 
Thanks. Fixed that. Debugger tells me there is an error with 'code' c.Select –  blahblahblahblah Jun 17 '13 at 19:01
add comment

When you don't define c as a range, the statement

For Each c in ActiveSheet.Range("Q5:U5").Cells

while valid, will actually result in c having the value of each of the cells. To solve this problem, declare the type explicitly:

Dim c as Range

Next, when you do the comparison (as already pointed out), use

If c.Value = "Y"

Note - if you declare

Option Compare Text

right at the top of your module, the comparison will be case-insensitive; otherwise, a "Y" will not match a "y".

The whole module would look like this, then:

Option Explicit
Option Compare Text

Sub colorMe()
Dim c as Range
For Each c In Range("Q5:U5").Cells
  c.Select
  If c.Value = "Y" Then
    With Selection.Interior
      .Pattern = xlSolid
      .PatternColorIndex = xlAutomatic
      .Color = 5287936
      .TintAndShade = 0
      .PatternTintAndShade = 0
    End With
  End If
Next
End Sub

I am sure it doesn't need to be pointed out that you could achieve the same thing with conditional formatting...

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.