error handlingVBA:什么时候没有错误?

我试图捕捉与VBA的一些错误,我发现这个教程 ,我想捕捉错误使用GoTo方法在下面的例子中:

 Sub mySub On Error GoTo myHandler: Workbooks.Open("myWorkbook") ' ' Some Code ' myHandler: MsgBox "EROOR !" End Sub 

问题是,即使没有错误, myHandler部分总是被执行! 我发现这个讨论,但提出的答案并不能解决问题
我试图添加一个Exit Sub语句,解释如下:

 Sub mySub On Error GoTo myHandler: Workbooks.Open("myWorkbook") Exit Sub ' ' Some Code ' myHandler: MsgBox "EROOR !" End Sub 

在这种情况下,即使没有错误,也会退出该方法。 我也试过:

  Sub mySub On Error GoTo myHandler: Workbooks.Open("myWorkbook") ' ' Some Code ' myHandler: MsgBox "EROOR !" Exit Sub End Sub 

但仍然是同样的问题,myHandler甚至没有错误执行。

只要把退出子。

 Sub mySub On Error GoTo myHandler: Workbooks.Open("myWorkbook") ' ' Some Code ' Exit sub myHandler: MsgBox "EROOR !" err.clear End Sub 

这是我喜欢的模式:

 Sub SomeSub() On Error GoTo ErrorLabel 'Code goes here ExitLabel: 'Clean-up code, if any, goes here Exit Sub ErrorLabel: 'Error-handling code goes here Resume ExitLabel End Sub 

请注意, Resume清除错误。 我喜欢这种模式有几个原因:

  1. 在error handling块之前习惯性地插入退出块可以减less出现意外丢入error handling程序的问题。
  2. 我使用GoTo ExitLabel任何提前离开小组或function。 这样,我不太可能不小心跳过清理代码。 例:

     Sub SomeOtherSub() Dim x As ResourceThatNeedsToBeClosed Dim i As Long On Error GoTo ErrorLabel Set x = GetX For i = 1 To 100 If x.SomeFunction(i) Then GoTo ExitLabel End If Next ExitLabel: x.Close ErrorLabel: 'Error-handling code goes here Resume ExitLabel End Sub 
 Public Sub MySub On Error Goto Skip ' Some Codes Skip: If err.Number > 0 Then ' Run whatever codes if error occurs err.Clear End If On Error Goto 0 End Su 

在error handling程序部分使用以下代码:

如果err.number> 0,则“error handling在此处结束”如果结束

我和你有完全相同的问题,上面的解决scheme不起作用。 他们显然甚至没有看到你已经在原来的post中的2个不同的地方写了Exit Sub。 没有在线网站似乎明白,有时不会有错误(如果总是会出现错误,为什么你要这样编码?),当没有错误时,你显然不会想要退出小组。 当没有错误时,你也不希望myHandler运行。 DUH! 这是我看来似乎工作的解决scheme。

 On Error GoTo ErrorHandler 'This is the thing I am trying to do... Workbooks("SpreadSolver.xlsb").Activate 'If it works, great. 'Don't touch the error stuff and move on. 'Ie go to the part that I know works (the rest of the macro) GoTo ThisPartWorks 'If the thing I am trying to do doesn't work... ErrorHandler: MsgBox "Error: Please open Spread Solver and then run the macro." 'Only want to Exit Sub if there is an error.. duh. Exit Sub ThisPartWorks: 'the rest of your macro can go here... '... End Sub