如何做一个像Try / Catch这样的内联error handling块

我如何在VBA中执行内联error handling例程? 我不想把error handling程序放在最后。

这是来自CPearson在VBA中的error handling

Sub testErrHandling() On Error GoTo ErrHandler: Debug.print 9 / 0 'divide by zero error Worksheets("NewSheet").Activate 'missing worksheet error 'more code here Exit Sub ErrHandler: If Err.Number = 9 Then ' sheet does not exist, so create it Worksheets.Add.Name = "NewSheet" ' go back to the line of code that caused the problem Resume End If End Sub 

但是我正在寻找更像VB.net中的Try / Catch块

您可以尝试在variables中分配对象,并使用On Error Resume Next替代。

 Dim sh As Worksheet 'This is essentially the "Try" part On Error Resume Next 'this ignores the error Set sh = Worksheets("NewSheet") On Error Goto 0 'this resets the active error handling routine 'Then this is the "Catch" part I guess If sh Is Nothing Then 'check is something is assigned to sh 'And I think this is "Finally" part Set sh = Worksheets.Add: sh.Name = "NewSheet" 'add otherwise End If 

对于Try / Catch并不是很熟悉,因为我没有做过一些VB.Net,但是这是我能想到的最接近的内联错误更正。 HTH。

此代码将处理内联错误。 这是处理错误的非常干净的结构化模式。 stream量从上到下非常干净地移动; 这里没有意大利面代码。

VBA是一种古老的语言,有其局限性。 使用error handling的方法之一是以On Error Goto <Label>Resume <Label>的forms使用Goto语句。 这创造了一个机会。

传统上,error handling程序位于底部。 但是随着VB.net的进步,利用想法来改进代码似乎是合理的。 Try / Catch是处理错误的非常结构化的方式,非常容易遵循。 这种模式试图以非常简洁的方式重现这一模式。 stream程非常一致,不会因地而异。

 Sub InLineErrorHandling() 'code without error handling BeginTry1: 'activate inline error handler On Error GoTo ErrHandler1 'code block that may result in an error Dim a As String: a = "Abc" Dim c As Integer: c = a 'type mismatch ErrHandler1: 'handle the error If Err.Number <> 0 Then 'the error handler is now active Debug.Print (Err.Description) End If 'disable previous error handler (VERY IMPORTANT) On Error GoTo 0 'exit the error handler Resume EndTry1 EndTry1: 'more code with or without error handling End Sub 

资料来源:

  • Pearson在VBA中的error handling
  • 如何处理VBA中的运行时错误
  • 正确处理VBA中的错误(Excel)

妥善pipe理这个作品相当好。 这是一个非常干净的stream动模式,可以在任何需要的地方重现。