Excel VBA 在同一过程中处理多个错误

标签 excel vba error-handling

我以前曾在 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/

相关文章:

excel - 如何确定单元格中是否已写入公式或手动输入

vba - 是否可以将其转换为数组/字典以使其更快

vba - 检查值是否在范围内而不循环

ruby-on-rails - ajax请求上的Ruby on Rails错误500

rest - asp.net Web Api - 默认错误消息

vba - Excel VBA "Autofill Method of Range Class Failed"

vba - Excel VBA - 粘贴为值

vba - 为什么 VBA PowerPoint 中的幻灯片创建循环不起作用?

excel - Find() 返回 "object variable or with block variable not set"

java - 使用 spring ExceptionHandler 时,声纳违规未检查/未确认的异常转换