excel-vba 错误处理

示例

良好的错误处理可以防止最终用户看到VBA运行时错误,并帮助开发人员轻松诊断和更正错误。

VBA中有三种主要的错误处理方法,对于分布式程序,应避免使用其中两种方法,除非代码中特别要求。

On Error GoTo 0 'Avoid using

要么

On Error Resume Next 'Avoid using

优先使用:

On Error GoTo <line> 'Prefer using


出错时转到0

如果您的代码中未设置任何错误处理,On Error GoTo 0则为默认错误处理程序。在这种模式下,任何运行时错误都会启动典型的VBA错误消息,从而使您可以结束代码或进入debug模式,从而确定源。在编写代码时,此方法是最简单,最有用的方法,但是对于分发给最终用户的代码,应始终避免使用此方法,因为此方法非常难看,并且最终用户很难理解。


关于错误继续

On Error Resume Next将导致VBA忽略错误调用之后所有行在运行时引发的任何错误,直到错误处理程序已更改。在非常特定的情况下,此行可能有用,但在这些情况下应避免使用。例如,当从Excel宏启动单独的程序时,On Error Resume Next如果不确定该程序是否已打开,则该调用将非常有用:

'In this example, we open an instance of Powerpoint using the On Error Resume Next call
Dim PPApp As PowerPoint.Application
Dim PPPres As PowerPoint.Presentation
Dim PPSlide As PowerPoint.Slide

'Open PPT if not running, otherwise select active instance
On Error Resume Next
Set PPApp = GetObject(, "PowerPoint.Application")
On Error GoTo ErrHandler
If PPApp Is Nothing Then
    'Open PowerPoint
    Set PPApp = CreateObject("PowerPoint.Application")
   PPApp.Visible= True
End If

如果我们不使用该On Error Resume Next调用并且Powerpoint应用程序尚未打开,则该GetObject方法将引发错误。因此,On Error Resume Next有必要避免创建应用程序的两个实例。

注意:最好的方法是在不再需要调用时立即重置错误处理程序On Error Resume Next


发生错误时转到<行>

建议将这种错误处理方法用于分发给其他用户的所有代码。这使程序员可以通过将代码发送到指定的行来精确控制VBA如何处理错误。标签可以用任何字符串(包括数字字符串)填充,并将代码发送到相应的字符串,后跟冒号。可以通过对进行不同的调用来使用多个错误处理块On Error GoTo <line>。下面的子例程演示了On Error GoTo <line>调用的语法。

注意:必须将Exit Sub行放置在第一个错误处理程序的上方以及每个后续错误处理程序的前面,以防止代码自然地前进到块中不会调用错误。因此,对于功能和可读性而言,最佳实践是将错误处理程序放在代码块的末尾。

Sub YourMethodName()
    On Error GoTo errorHandler
    ' Insert code here
    On Error GoTo secondErrorHandler

    Exit Sub 'The exit sub line is essential, as the code will otherwise
             'continue running into the error handling block, likely causing an error

errorHandler:
    MsgBox "Error " &Err.Number& ": " &Err.Description& " in " & _
        VBE.ActiveCodePane.CodeModule, vbOKOnly, "Error"
    Exit Sub

secondErrorHandler:
    IfErr.Number= 424 Then 'Object not found error (purely for illustration)
       Application.ScreenUpdating= True
       Application.EnableEvents= True
        Exit Sub
    Else
        MsgBox "Error " &Err.Number& ": " & Err.Desctription
       Application.ScreenUpdating= True
       Application.EnableEvents= True   
        Exit Sub
    End If      
    Exit Sub

End Sub

如果使用错误处理代码退出方法,请确保进行清理:

  • 撤消部分完成的操作

  • 关闭档案

  • 重置屏幕更新

  • 重置计算模式

  • 重置活动

  • 重置鼠标指针

  • 对对象实例调用卸载方法,该实例在 End Sub

  • 重置状态栏