从For-Next循环中前进到下一个项目

时间:2014-04-14 14:38:20

标签: excel vba excel-vba

我有一个For-Next循环。在循环中我测试了几个不同的标准,如果任何测试失败,那么我准备在那一点跳过循环中的其余代码并前进到" next"项目。我目前处理这个问题的方法是使用GoTo语句将我带到#34; Next"之前的行。我不想使用GoTo声明,是否有另一种方式可以进入" next" For-Next循环中的项目? TIA!

For x = 1 to 10
    Test 1
    If Test 1 fails then
        GoTo Line1
    End if

    Test 2
    If Test 2 fails then
        GoTo Line1
    End if
    .
    .
    .
    If all tests pass then
        add item to array
    End if
Line1:    
Next

5 个答案:

答案 0 :(得分:4)

不幸的是,在vba的continue循环中没有类似for的语句。 (相关的控制结构Exit For确实存在,但这里没有帮助。)

如果您对使用GoTo有所保留,那就太好了:它们确实使代码难以理解。

最好的办法是将代码放在循环中的单独函数中,并在适当的位置使用该函数中的Exit Function。您甚至可以将错误代码传回给调用者,以帮助代码扩展。

答案 1 :(得分:1)

以下是缺少continue关键字的解决方法:

For x = 1 to 10
    Do
        Test 1
        If Test 1 fails then
            Exit Do
        End if

        Test 2
        If Test 2 fails then
            Exit Do
        End if
        .
        .
        .
        If all tests pass then
            add item to array
        End if
    Loop While False
Next

答案 2 :(得分:0)

你可以使用if else ladder:

For x = 1 to 10
if test 1 
else if test 2
else if test 3
. 
.
.
.
else
  add item to array
end if
Next

除了GoTo,没有任何直接的方法可以在你的代码之间跳转, 希望这可能有所帮助。

答案 3 :(得分:0)

如果没有太多测试,可以使用Not条件并构建嵌套的If语句。这应该与您要求的效果几乎相同,因为任何失败的测试都会结束If语句并将代码移动到循环中的下一个X而不执行以下测试。

这是我的意思的一个例子 - 一个构建包含数字5到10的数组的两个测试循环:

Sub TestConditionalPass()

    Dim intX As Integer
    Dim intArray() As Integer
        ReDim intArray(1)

    For intX = 1 To 10
        If Not intX -2 < 1 Then
            If Not intX * 2 < 10 Then
                ReDim Preserve intArray(UBound(intArray) + 1)
                    intArray(UBound(intArray)) = intX
            End If
        End If
    Next intX

End Sub

答案 4 :(得分:0)

由于只有在所有测试都成功时才执行操作,然后使用ands执行if语句。 VBA doesn't short circuit测试,(即它将评估每个测试用例,即使第一个返回false。)我建议将每个测试封装在一个返回布尔值的函数中,以保持代码整洁。

If Test1()  and _
   Test2()  and _
   testn()  THEN
    add item to array
End if

另一种方法是在代码中使用布尔变量,比如

Dim Success as Boolean
Success=True
Test 1
If Test 1 fails then
    Success=false
End if

Test 2
If Test 2 fails then
    Success=false
End if
.
.
.
If Success then
    add item to array
End if

如果测试很昂贵,你可以添加一个内部if语句检查,看看我们是否需要像这样评估下一个测试

 If Success Then
    If Test n fails then
       Success=false
    End If
End if