对于循环不完整

时间:2017-03-06 08:16:38

标签: excel-vba if-statement for-loop vba excel

我得到一个错误,我的下一个是没有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

2 个答案:

答案 0 :(得分: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语句匹配。除了确保您的代码有效之外,它还将使其更易于阅读。 (请注意,我尝试编辑你的问题以缩进代码[我们经常做的事情是为了让其他试图回答你问题的人更容易]并且没有任何陈述排成一行 - 我最终放弃了因为两个{{ 1}}语句只有一个块Else以匹配它们。)

答案 1 :(得分:0)

你已经开始了两个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