前进到下一个循环中的下一个项目

我有一个For-Next循环。 在循环中,我testing了几个不同的标准,如果有任何testing失败,那么我准备好跳过循环中的其余代码并前进到“下一个”项目。 我目前处理这个问题的方法是使用GoTo语句,该语句将我带到“Next”之前的那一行。 我不想使用GoTo语句,是否有另一种方法可以在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 

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

 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 

不幸的是for在VBA的for循环中没有类似continue的声明。 (相关的控制结构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之外,没有任何直接的方法可以在你的代码之间跳转,希望这可能有帮助。

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

下面是我的意思的一个例子 – 一个两个testing循环,构build一个包含数字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 

由于只有在所有testing都成功的情况下才执行动作,则使用ands来执行if语句。 VBA不会将testing短路 (即,即使第一个testing用例返回false,也会评估每个testing用例)。我build议将每个testing封装在返回布尔值的函数中,以保持代码整洁。

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

另一种方法是在你的代码中使用一个布尔variables,像这样

 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 

如果testing是昂贵的,你可以添加一个内部if语句来检查是否需要像这样评估下一个testing

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