Dav*_*vid 3 error-handling excel vba
我以前在 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
...
Run Code Online (Sandbox Code Playgroud)
第二个错误处理块不起作用。我猜我没有正确退出第一个错误处理块。试图找到一个对我有用但没有成功的答案。
非常感谢任何帮助!
在一个过程中有两个或多个错误处理子程序绝对是一种设计味道;这不是 VBA 错误处理的工作方式。
基本上你有这个:
Sub Foo()
On Error GoTo ErrHandler1
'(code)
ErrHandler1:
'(error handling code)
On Error GoTo ErrHandler2
'(code)
ErrHandler2:
'(error handling code)
End Sub
Run Code Online (Sandbox Code Playgroud)
当第一个块中发生错误时,VBA 跳转到ErrHandler1 第二个块时仍然认为它在错误处理子例程中。
你需要在Resume某个地方告诉 VBA“我已经处理了我必须处理的所有事情”。
因此NoError1,您的ErrorHandler1子程序应该以Resume跳转结束,而不是“落入”子程序:
Resume NoError1
Run Code Online (Sandbox Code Playgroud)
并且ErrorHandler2还应该以Resume跳转结束:
Resume NoError2
Run Code Online (Sandbox Code Playgroud)
这样 VBA 就知道它已退出“错误处理模式”并返回“正常执行”。
但我强烈建议考虑单独的方法/过程而不是标记的子程序。
| 归档时间: |
|
| 查看次数: |
17210 次 |
| 最近记录: |