【问题标题】:VBA Error handling and find if I can resume or notVBA错误处理并查找我是否可以恢复
【发布时间】:2021-09-01 14:00:56
【问题描述】:

我已经使用 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

【问题讨论】:

  • 这能回答你的问题吗? Resume statement
  • 可以分享一下//code...吗?您将如何修复错误以使脚本继续打印?改变纸张格式?为什么这是一个愚蠢的错误?如果您修复了If 部分中的错误,则可以使用Resume 继续引发错误的行。如果不修复,Resume 会导致死循环。如果您打算继续下一行,则必须使用Resume Next
  • @VBasic2008 代码并不是重点,因为它只是与单词和复制/粘贴的连接。我认为这很愚蠢,因为人们可以在 Microsoft Word 中手动更改纸张格式,纸张大小只是一种偏好。如果 Err.Number = 5889,我会使用 Err.clear 继续,而不会陷入无限循环。如果我使用 resume next 它不会回到以前的位置,因为它现在在 ErrHand: 部分...
  • @АлексейР 我认为这正是我所需要的,但很明显,我并没有对此表示怀疑......但是你能解释一下简历行号是如何工作的吗? VBA 不再有行号。如果我不知道它必须从哪里恢复,有没有办法得到这个数字?
  • 行号(例如110:)类似于行标签(例如my_label:),但由数字组成 - (docs.microsoft.com/en-us/office/vba/language/glossary/…)。我认为可能最好使用Resume Next @VBasic2008 写道

标签: excel vba error-handling


【解决方案1】:

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

    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

【讨论】:

  • 摆脱 IgnorableReEntry 并像 cmets 中建议的那样使用 Resume Next。
  • 修改为使用Resume Next
猜你喜欢
  • 2014-02-20
  • 2010-09-24
  • 2015-06-06
  • 2021-04-03
  • 1970-01-01
  • 2012-03-03
  • 1970-01-01
  • 1970-01-01
  • 2017-04-16
相关资源
最近更新 更多