【问题标题】:Excel VBA: Single Loop + If-Statement; Run-time Error 1004Excel VBA:单循环+如果语句;运行时错误 1004
【发布时间】:2018-04-16 05:23:31
【问题描述】:

我想遍历一列并将该范围内的所有单元格与单元格“AD2”的值 x 进行比较。如果单元格 i 的值小于值 x,我希望单元格 i 标记为红色。运行以下代码时:

Sub Button10()
    Dim i As Long
    Dim x As Integer
    x = Range("AD2").Value
    If Cells(i, 26).Value < x Then
        Cells(i, 26).Font.Color = vbRed
        For i = 1 To 500
        Next i
    End If
End Sub

我收到以下错误:

运行时错误“1004”:对象“范围”的方法“_Default”失败。

【问题讨论】:

  • Google For Loop vba 您的循环不正确。 for 循环应该在 if 之前和之后的 Next 不在 if 内。
  • 再看一遍,For-Loop逻辑明显有缺陷,谢谢提示!

标签: vba excel for-loop if-statement


【解决方案1】:

现在我已经indented your code,希望你能看到你的逻辑在你的For 循环之外,而它应该在它里面。

您会收到一个错误,因为当您声明 i As Long 时,它会使用 0 的值进行初始化。因此,此行将失败,因为 i = 0 没有返回有效范围:

If Cells(i, 26).Value < x Then

所以试试这个:

Sub Button10()
    Dim i As Long
    Dim x As Integer
    x = Range("AD2").Value
    For i = 1 To 500
        If Cells(i, 26).Value < x Then
            Cells(i, 26).Font.Color = vbRed
        End If
    Next i
End Sub

【讨论】:

  • 感谢链接到 Rubberduck 的缩进页面。请注意,将 OP 的代码粘贴到 inspections page 中(有点耐心......网络托管的构建比实际的 IDE 内 Rubberduck 安装要慢得多),会发现更多的问题正在咆哮和露出牙齿,等待有机会在 ...后端咬 OP。
  • 感谢您的澄清!我可以看到,For-Loop 逻辑和 If 语句对我的旧安排没有意义。也感谢你提供了很棒的 vba-intender 工具,会使用它:)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多