【问题标题】:How to Loop Through 5 Cells in a Row Using Excel VBA如何使用 Excel VBA 连续遍历 5 个单元格
【发布时间】:2013-06-13 20:00:02
【问题描述】:

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

【问题讨论】:

    标签: vba excel for-loop excel-2007


    【解决方案1】:

    您应该尽量避免选择/激活范围:在 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
    

    【讨论】:

      【解决方案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
      

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

      【讨论】:

        【解决方案3】:

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

        If c.Value = "Y" Then

        【讨论】:

        • 谢谢。解决了这个问题。调试器告诉我“代码”c.Select 有错误
        猜你喜欢
        • 1970-01-01
        • 2017-05-14
        • 2021-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-18
        相关资源
        最近更新 更多