VBA 错误处理并确定我是否可以恢复

VBA Error handling and find if I can resume or not

我已经使用 VBA 很长时间了,但我找不到我需要的关于错误处理的内容。这是我的问题:

我希望 VBA 将数据从 Excel 放入 Word,但有时我会收到类似“未找到纸张格式”的错误,因为其中一台电脑没有合法纸张,这会停止不应该的程序,因为它是一个愚蠢的错误。

这是我用来处理错误的代码:

Public Sub print_data()

Application.ScreenUpdating = False
Application.EnableEvents = False

On Error GoTo ErrHand 

//code...

ExitHand:
    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Sheets("Login").Select
    Exit Sub

ErrHand:
    MsgBox "Error." & Chr(13) & Chr(13) & Err.Number & ": " & Err.Description, vbCritical, "Error"
    Resume ExitHand

我想做的事情:

On Error GoTo ErrHand 

//code...

ExitHand:
    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Sheets("Login").Select
    Exit Sub

ErrHand:
    'if error is the paper size (err 5889) continue else end sub
    If Err.Number = 5889 then
        'Go back where the error happened then resume next
    Else
        Resume ExitHand
    end if

示例中的部分困难在于,代码将 ErrorHandling 混合使用以保证重置操作与 ErrorHandling 以检查特定的逻辑条件。如果您将这些关注点分开,则会导致更简单的逻辑。在不知道“//代码”的细节的情况下,请考虑以下内容:

    Public Sub print_data()

        Application.ScreenUpdating = False
        Application.EnableEvents = False
        
        'SafePrintData does not generate any errors
        SafePrintData
        
        Application.ScreenUpdating = True
        Application.EnableEvents = True
        Sheets("Login").Select
    End Sub

    '//code goes in here...but partitioned to capture specific errors
    Private Sub SafePrintData()

    On Error GoTo ExitOnError
        'Code line(s)
        
    On Error GoTo IgnorableError
        'Code line that can generate 5889

    On Error GoTo ExitOnError
        'Code line(s)
        
    ExitOnError:
        Exit Sub
        
    IgnorableError:
        If Err.Number = 5889 Then
            Resume Next
        Else
            MsgBox "Error." & Chr(13) & Chr(13) & Err.Number & ": " & Err.Description, vbCritical, "Error"
            Resume ExitOnError
        End If
        
    End Sub