如何使用Excel VBA连续循环5个单元格

bla*_*lah 3 excel vba for-loop excel-2007 excel-vba

我想循环通过5个细胞,Q5 - U5.

对于每个单元格,我想检查该值是否等于"Y",如果是,则突出显示该单元格以使其变为绿色.

我该怎么办?似乎无法弄明白.

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
Run Code Online (Sandbox Code Playgroud)

Tim*_*ams 9

您应该尽量避免选择/激活范围:在99%的情况下没有必要(尽管宏录制器总是另有建议)

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
Run Code Online (Sandbox Code Playgroud)