简体   繁体   English

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

[英]How to Loop Through 5 Cells in a Row Using Excel VBA

I want to loop through 5 cells, Q5 - U5. 我想循环通过5个细胞,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. 对于每个单元格,我想检查该值是否等于“Y”,如果是,则突出显示单元格使其变为绿色。

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

You should try to avoid selecting/activating ranges: in 99% of cases there is no need (although the macro recorder always suggests otherwise) 您应该尽量避免选择/激活范围:在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

When you don't define c as a range, the statement 当您没有将c定义为范围时,语句

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

while valid, will actually result in c having the value of each of the cells. 虽然有效,但实际上会导致c具有每个单元格的值。 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". 否则,“Y”将与“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... 我确信不需要指出你可以用条件格式来实现同样的目的......

In your code, Y appears to be an undefined variable. 在您的代码中, Y似乎是一个未定义的变量。 To check for the value, put it in double quotes: 要检查值,请将其放在双引号中:

If c.Value = "Y" Then

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM