我以前曾在 VBA 中成功使用过错误处理,但是当尝试使用多个错误处理 block 时,我不知道如何操作。
我编写的代码如下所示:
...
On Error GoTo ErrorHandler1
shpArrow1.Left = shpLine.Left + shpLine.Width * Min(Sqr(Calculations.Range("cVolProduct").value / Calculations.Range("cVolRefIndices").value), 2) / 2 - shpArrow1.Width / 2
shpTag1.Left = shpLine.Left + shpLine.Width * Min(Sqr(Calculations.Range("cVolProduct").value / Calculations.Range("cVolRefIndices").value), 2) / 2 - shpTag1.Width / 2
shpArrow2.Left = shpLine.Left + shpLine.Width * Min(Sqr(Calculations.Range("cVolUnderlyings").value / Calculations.Range("cVolRefIndices").value), 2) / 2 - shpArrow2.Width / 2
shpTag2.Left = shpLine.Left + shpLine.Width * Min(Sqr(Calculations.Range("cVolUnderlyings").value / Calculations.Range("cVolRefIndices").value), 2) / 2 - shpTag2.Width / 2
shpIndexLine.Left = shpLine.Left + shpLine.Width / 2 - shpIndexLine.Width / 2
GoTo NoError1
ErrorHandler1:
shpArrow1.Left = shpLine.Left - shpArrow1.Width / 2
shpTag1.Left = shpLine.Left - shpTag1.Width / 2
shpArrow2.Left = shpLine.Left - shpArrow2.Width / 2
shpTag2.Left = shpLine.Left - shpTag2.Width / 2
shpIndexLine.Left = shpLine.Left + shpLine.Width / 2 - shpIndexLine.Width / 2
errorRelativeRisk = 1
NoError1:
On Error GoTo 0
On Error GoTo ErrorHandler2
Output.ChartObjects("ChartHistoryUnderlyings").Activate
ActiveChart.Axes(xlValue).CrossesAt = ActiveChart.Axes(xlValue).MinimumScale
ActiveChart.Axes(xlCategory).CrossesAt = ActiveChart.Axes(xlCategory).MinimumScale
GoTo NoError2
ErrorHandler2:
errorHistUnderl = 1
NoError2:
On Error GoTo 0
...
第二个错误处理 block 不起作用。我猜我没有正确退出第一个错误处理 block 。试图找到适合我的答案,但没有成功。
非常感谢您的帮助!
最佳答案
在一个过程中有两个或多个错误处理子例程绝对是一种设计味道;这不是 VBA 错误处理的工作原理。
基本上你有这个:
Sub Foo()
On Error GoTo ErrHandler1
'(code)
ErrHandler1:
'(error handling code)
On Error GoTo ErrHandler2
'(code)
ErrHandler2:
'(error handling code)
End Sub
当第一个 block 中发生错误时,VBA 跳转到 ErrHandler1
并且当到达第二个 block 时仍然认为它处于错误处理子例程中。 p>
您需要在某个地方Resume
,告诉VBA“我已经处理了我必须处理的所有事情”。
因此,您的 ErrorHandler1
子例程不应“落入”NoError1
子例程,而应以 Resume
跳转结束:
Resume NoError1
并且 ErrorHandler2
也应该以 Resume
跳转结束:
Resume NoError2
这样,VBA 就知道它已退出“错误处理模式”并返回“正常执行”状态。
但我强烈建议考虑单独的方法/过程,而不是标记的子例程。
关于Excel VBA 在同一过程中处理多个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33877029/