我在数组上有一个for循环。我想要做的是测试循环中的某个条件,如果为true,则跳到下一个迭代:
For i = LBound(Schedule, 1) To UBound(Schedule, 1)
If (Schedule(i, 1) < ReferenceDate) Then
PrevCouponIndex = i
Continue '*** THIS LINE DOESN'T COMPILE, nor does "Next"
End If
DF = Application.Run("SomeFunction"....)
PV = PV + (DF * Coupon / CouponFrequency)
Next
我知道我能做到:
If (Schedule(i, 1) < ReferenceDate) Then Continue For
但我希望能够在PrevCouponIndex变量中记录i的最后一个值。
有什么想法吗?
由于
答案 0 :(得分:165)
VBA没有Continue
或任何其他等效关键字可以立即跳转到下一个循环迭代。我建议明智地使用Goto
作为解决方法,特别是如果这只是一个人为的例子而且你的真实代码更复杂:
For i = LBound(Schedule, 1) To UBound(Schedule, 1)
If (Schedule(i, 1) < ReferenceDate) Then
PrevCouponIndex = i
Goto NextIteration
End If
DF = Application.Run("SomeFunction"....)
PV = PV + (DF * Coupon / CouponFrequency)
'....'
'a whole bunch of other code you are not showing us'
'....'
NextIteration:
Next
如果这真的是你的所有代码,那么@Brian是绝对正确的。只需在Else
语句中添加If
条款即可完成。
答案 1 :(得分:29)
难道你不能做这样简单的事吗?
For i = LBound(Schedule, 1) To UBound(Schedule, 1)
If (Schedule(i, 1) < ReferenceDate) Then
PrevCouponIndex = i
Else
DF = Application.Run("SomeFunction"....)
PV = PV + (DF * Coupon / CouponFrequency)
End If
Next
答案 2 :(得分:21)
您可以使用嵌套continue
:
Do ... Loop While False
'This sample will output 1 and 3 only
Dim i As Integer
For i = 1 To 3: Do
If i = 2 Then Exit Do 'Exit Do is the Continue
Debug.Print i
Loop While False: Next i
答案 3 :(得分:13)
Continue For
在VBA或VB6中无效。
从this MSDN page开始,它似乎已经在VS 2005./Net 2中引入VB.Net。
正如其他人所说,除了使用Goto
或Else
之外别无选择。
答案 4 :(得分:1)
您好我也面临这个问题,我使用下面的示例代码
解决了这个问题For j = 1 To MyTemplte.Sheets.Count
If MyTemplte.Sheets(j).Visible = 0 Then
GoTo DoNothing
End If
'process for this for loop
DoNothing:
Next j
答案 5 :(得分:-2)
也许尝试把它全部放在最后如果并使用else来跳过代码,这将使它无法使用GoTo。
If 6 - ((Int_height(Int_Column - 1) - 1) + Int_direction(e, 1)) = 7 Or (Int_Column - 1) + Int_direction(e, 0) = -1 Or (Int_Column - 1) + Int_direction(e, 0) = 7 Then
Else
If Grid((Int_Column - 1) + Int_direction(e, 0), 6 - ((Int_height(Int_Column - 1) - 1) + Int_direction(e, 1))) = "_" Then
Console.ReadLine()
End If
End If