【问题标题】:For loop incompletefor循环不完整
【发布时间】:2017-03-06 08:16:38
【问题描述】:

我收到一个错误,我的下一个没有 for :/ 我在这里想念什么。我希望它检查C列(单元格(y,3)),如果它是空白的,那么查看A列,在G中找到匹配的值,然后在C列的F中给出相应的值。如果它不是空白的,然后垂直移动到下一个单元格。

    Dim x As Double
    Dim y As Double
    For y = 2 To 84212
        For x = 531 To 632

            If IsEmpty(Cells(y, 3)) Then
                If Cells(y, 1).Value = Cells(x, 6).Value Then Cells(y, 3).Value = Cells(x,7).Value
            Else: Next x
            Else: Next y
End Sub

【问题讨论】:

标签: excel if-statement for-loop vba


【解决方案1】:

您的循环和 If 语句应如下所示:

Dim x As Long ' Use Long, rather than Double for integer arithmetic
Dim y As Long
For y = 2 To 84212
    If IsEmpty(Cells(y, 3)) Then ' Perform this test before starting the 
                                 ' inner loop, thus saving 102 iterations
        For x = 531 To 632
            If Cells(y, 1).Value = Cells(x, 6).Value Then
                Cells(y, 3).Value = Cells(x, 7).Value
                Exit For ' No use looking at other "x" rows once a match has been found
            End If
        Next x
    End If
Next y

还要注意缩进代码如何让您正确确保If 语句与End If 匹配,For 语句与Next 语句匹配。除了确保您的代码有效之外,它还将使其更易于阅读。 (请注意,我尝试编辑您的问题以缩进代码[我们经常做的事情是为了让其他试图回答您的问题的人更容易]并且没有一个陈述排队 - 我最终放弃了因为两个@987654327 @ 语句只有一个 Block If 来匹配它们。)

【讨论】:

  • 在我编写代码时VBA本身是否会为我缩进,还是必须手动完成?
  • 关于x上的for循环,为什么没有else,如果不匹配,不应该给它一个语句然后移动到下一个x上?
  • @IsraShaikh - 如果If 语句没有Else 分支,则如果逻辑表达式的计算结果为False,则不执行任何操作 - 执行只是向下移动到@987654332 之后的任何内容@.
  • @IsraShaikh 重新缩进,VBA IDE 不会自动为您缩进,但有可用的加载项。我不使用任何东西,但我认为我可以推荐 RubberDuck(请参阅stackoverflow.com/a/29991570/6535336),因为两个(至少)更好的 VBA 问题 SO 回答者(comintern 和 Mat's Mug)参与了它的开发。 iDevlop 还添加了一个链接,作为对您的问题的评论,推荐另一个插件。
【解决方案2】:

您已经启动了两个 FOR 循环,但没有结束任何一个。您只需将它们放在 Else 语句中,而不是结束 IF:

Dim x As Double
Dim y As Double
For y = 2 To 84212
For x = 531 To 632

If IsEmpty(Cells(y, 3)) Then
If Cells(y, 1).Value = Cells(x, 6).Value Then Cells(y, 3).Value = Cells(x,7).Value Then
'Do something
End if
End if

Next x ' End loop with x variable
Next y ' End loop with y variable
       ' Both x and y can be omitted. This is just for clarifications.
End Sub

【讨论】:

  • 您的If <expression> Then <statement> Then 语句将不起作用。
猜你喜欢
  • 1970-01-01
  • 2012-07-08
  • 1970-01-01
  • 1970-01-01
  • 2018-11-24
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
  • 2022-01-04
相关资源
最近更新 更多