忽略“下标超出范围”的错误一次,以处理第一次迭代

我正在制作一个循环,用来计算弹丸的弹道,当弹丸与目标高度相同时弹丸就要停下来,并且弹丸处于正常状态。 这是由直到…线保证。 但是,当循环开始时,y(i-2)不存在[y(-1)],导致“运行时错误”9' – 下标超出范围“。 使用“On Error Resume Next”确实可以让循环继续,但是我经常会犯错误,并且当向循环中添加更多的东西(例如移动目标,偏航,风等)时肯定会出错。 由于这个原因,我想vba忽略运行时错误只有一次,并打破任何以下错误。

相关的代码部分如下:

vx(0) = V * Cos(Theta) 'set the initial conditions vy(0) = V * Sin(Theta) vz(0) = 0 x(0) = 0 y(0) = 0 z(0) = 0 i = 1 t = 0 On Error Resume Next Do Until y(i - 1) < TargetAlt And y(i - 1) < y(i - 2) 'Stop when the projectile is at the same height 'as the target AND the projectile in on the 'decent of its trajectory 'If the projectile is moving up then drag and gravity are working together 'If not drag is working against gravity. If vy(i - 1) > 0 Then vy(i) = vy(i - 1) + h * (-g - (DragCof * (vy(i - 1) ^ 2))) Else: vy(i) = vy(i - 1) + h * (-g + (DragCof * (vy(i - 1) ^ 2))) End If 'The y position of the projectile y(i) = y(i - 1) + h * (vy(i - 1)) 'x direction velocity vx(i) = vx(i - 1) + h * (-DragCof * (vx(i - 1) ^ 2)) 'The x position of the projectile x(i) = x(i - 1) + h * (vx(i - 1)) 'z direction velocity 'The z position of the projectile 'parameters t = t + h i = i + 1 Loop 

在i = 2处启动循环并相应地调整初始条件可能会起作用,但是如果可能,我想避免这种情况。

在某些特殊情况下,除了使用On Error Resume Next进行stream量控制外别无select,但这不是其中之一。 在这种情况下,这只会让你痛苦。

通过稍微移动你的逻辑,你可以更简单地处理第一个迭代边缘情况。 例如,停止标准检查可以像这样移动到循环的底部:

 Do '... code to calculate projectile position at this time step... 'Advance to next time step t = t + h i = i + 1 'Get out when projectile falls below target height AND is on descent Loop Until y(i - 1) < TargetAlt And y(i - 1) < y(i - 2)