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

时间:2015-03-11 07:16:15

标签: excel vba excel-vba excel-vba-mac

我正在制作一个计算弹丸轨迹的循环,并希望当弹丸与目标处于同一高度并且弹丸位于体面时,循环停止。 Do Until ...行确保了这一点。但是,当循环开始时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处开始循环并相应地调整初始条件可能会起作用,但是如果可能的话我想避免这种情况。

1 个答案:

答案 0 :(得分:3)

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

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

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)