3

我想循环通过 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
4

3 回答 3

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
于 2013-06-17T19:38:49.203 回答
2

当您不将 c 定义为范围时,该语句

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

虽然有效,但实际上会导致c每个单元格的值。要解决此问题,请显式声明类型:

Dim c as Range

接下来,当您进行比较时(如前所述),使用

If c.Value = "Y"

注意 - 如果您声明

Option Compare Text

在模块的顶部,比较将不区分大小写;否则,“Y”将不匹配“y”。

整个模块看起来像这样,然后:

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

我确信不需要指出您可以使用条件格式来实现相同的目标......

于 2013-06-17T20:56:28.443 回答
0

在您的代码中,Y似乎是一个未定义的变量。要检查该值,请将其放在双引号中:

If c.Value = "Y" Then

于 2013-06-17T18:58:38.247 回答