2015-01-07 38 views
1

如何在VBA中進行內聯錯誤處理例程?我不想把錯誤處理程序放在最後。如何做一個內聯的錯誤處理塊,如Try/Catch

這是CPearson's Error Handling in VBA

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

+0

VBA比VB.NET要舊得多,並且沒有一個做try/catch塊的等效方法。你可以用一個相當奇怪的語法和多個goto來僞造它,但我認爲沒有必要這樣做。 –

+0

@ vba4all你應該查看下面的答案。我爲我的創新感到自豪。如果你願意,你可以稱它很奇怪,但歷史往往超越了反對者的進步。它當然是不錯的代碼恕我直言。 –

+0

我確實看到你在那裏做了什麼,但對我來說'Resume EndTry1'沒有什麼不同,然後說'GoTo '和隨機'goto'是壞習慣,應該不惜一切代價避免。順便說一句,你在這裏做了什麼[已普遍已知多年](http://www.vbforums.com/showthread.php?448403-Classic-VB-Why-do-errors-crash-my-program-and-我怎麼可以停止這種發生)*在SO *上可能沒有提及。 –

回答

2

此代碼將處理錯誤內嵌一個try/catch塊。這是處理錯誤的非常乾淨的結構化模式。流量從上到下非常乾淨地移動;這裏沒有意大利麪代碼。

VBA是一種古老的語言,有其侷限性。使用錯誤處理的方法之一是使用語句,格式爲On Error Goto <Label>Resume <Label>。這創造了一個機會。

傳統上錯誤處理程序位於底部。但隨着VB.net的進步,利用想法來改進代碼似乎是合理的。 Try/Catch是處理錯誤的非常結構化的方式,非常容易遵循。這種模式試圖以非常簡潔的方式重現這一模式。流程非常一致,不會從一個地方跳到另一個地方。

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 

來源:

正確管理這個工程相當不錯。這是一種非常乾淨的流動模式,可在任何需要的地方重現。

+0

嘗試在現實世界的環境 - *如果你知道我的意思*;) –

2

您可以嘗試分配變量中的對象並使用代替錯誤繼續下一步

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。

+0

這是一個很好的例子,如何解決這個具體問題。但更廣泛的問題是如何做錯誤處理內聯。 –

+0

@D_Bester這正是我所提供的。 OERN + OEG0實際上給了你'Try'部分。之後,您可以實際選擇一個「Select Case」或「If」(它將用作您的「Catch」)以查找可能的錯誤編號並作出相應的反應。我同意vba4all關於'Goto'的使用,以儘可能避免它。我把自己限制爲1每個代碼的'Goto' :)那就是我。這可能並非如此。 – L42

+0

優秀的代碼,我同意!這種方法可以解決很多問題。我會稱之爲Try/Test方法。它確實解決了內聯錯誤。 –