[英]Advance to Next Item from Within a For-Next Loop
我有一個For-Next循環。 在循環中,我測試了幾個不同的條件,如果任何測試失敗,那么我准備跳過該循環中的其余代碼,進入“下一個”項目。 我當前處理此問題的方式是使用GoTo語句,該語句將我帶到“下一步”之前的那一行。 我不希望使用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
不幸的是,vba中的for
循環中沒有類似continue
的語句。 (相關的控制結構Exit For
確實存在,但這對您沒有幫助)。
最好保留使用GoTo
:它們確實使代碼難以遵循。
最好的選擇是將代碼放入單獨的函數中的循環中,並在適當的位置使用該函數中的Exit Function
。 您甚至可以將錯誤代碼中繼回調用者,從而幫助擴展代碼。
以下是缺少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
您可以使用if else梯形圖:
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語句。 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 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.