[英]EXCEL VBA - Loop through cells in a row, if not empty, copy cell value into another row until next row not empty
[英]How to Loop Through 5 Cells in a Row Using 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
您应该尽量避免选择/激活范围:在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
当您没有将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
我确信不需要指出你可以用条件格式来实现同样的目的......
在您的代码中, Y
似乎是一个未定义的变量。 要检查值,请将其放在双引号中:
If c.Value = "Y" Then
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.