我有一个数组的 for 循环。我想要做的是测试循环中的某个条件,如果为真则跳到下一次迭代:
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 的最后一个值。
有什么想法吗?
谢谢
最佳答案
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 是绝对正确的。只需在 If
语句中添加一个 Else
子句即可完成。
关于VBA - 如何有条件地跳过 for 循环迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8680640/