我有一个下一个循环。在循环中,我测试了几个不同的标准,如果任何测试失败,那么我已经准备好跳过循环中的剩余代码并前进到"下一个"项目。我目前处理这个问题的方式是使用GoTo语句,将我带到"Next"之前的行。我宁愿不使用GoTo语句,是否有另一种方法可以从For-Next循环中前进到"next"项目?蒂娅!

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
有帮助吗?

解决方案

这是缺少世代odicetagcode关键字的解决方法:

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
.

其他提示

不幸的是没有 continue-就像一个 for 在vba中循环。(相关的控制结构 Exit For 确实存在,但这在这里没有帮助)。

你对使用一个 GoTo:他们确实使代码难以遵循。

你最好的选择是将循环中的代码放在一个单独的函数中,并使用 Exit Function 在适当的点的功能内。您甚至可以将错误代码中继回呼叫者,以便帮助代码扩展。

如果梯子可以使用:

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之外,您的代码之间没有任何直接的方法, 希望这可能有所帮助。

如果你没有太多的测试,你可以使用 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

由于您只有在所有测试成功时才能进行操作,然后使用ANDS进行if-state。 vba没有短路测试,(即它将评估每个测试用例,即使第一个返回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
.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top