【发布时间】:2016-02-25 21:54:16
【问题描述】:
我之前在 VBA 中成功使用过错误处理,但是在尝试使用多个错误处理块时,我不知道该怎么做。
我写的代码是这样的:
...
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
...
第二个错误处理块不起作用。我猜我没有正确退出第一个错误处理块。试图找到适合我但没有成功的答案。
非常感谢您的帮助!
【问题讨论】:
-
...分别代表Private Sub DoSomething()和End Sub,还是有更多含义?我认为如果您在每个“块”之外extracted a method,您的代码可能更容易理解,每个“块”都有自己的错误处理;基本上你需要解开这个GoTo Mess。 -
是的,
...代表 sub 的开始和结束,但是有一些更简单的计算不应该影响错误处理。如果我只使用其中一个,基本上这两个错误处理块都可以工作,但是要同时使用这两个块,我可能必须通过制作两个短子来“隐藏”代码。
标签: excel vba error-handling