Question : Error Handling VBA

Hi Experts,

Simple one here. Is error handling always required. I haven't been using it thus far, but I've seen it in other code etc...How do I know when I need it, and where should it go in the code? is there a set standard in terms of where it should be placed or is it entirely dependent on the code and instructions being written.
I've seen it sometimes at the end , is that the best place for it? Or, can I get by without it?

any pointers would be great!

Thanks and cheer:-)

Answer : Error Handling VBA

On Error Resume Next should generally be used only in simple single purpose subs and functions that are called by your main subs (e.g. checking of a workbook is open or a sheet exists). Beyond that, error handling is really for catching unexpected errors or errors that you cannot readily handle in any other way. Typically you have an:

On Error Goto err_handler

line at the start (where 'err_handler' is a label in your code)

then an error handler section at the end, which in my case usually returns you to a clean-up section at the end of the code. For example:


1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rngCell As Range, strPrefix As String
    
   On Error GoTo Worksheet_Change_Error
    
    Application.EnableEvents = False
    
    If Not Intersect(Target, Range("A:A")) Is Nothing Then
        strPrefix = Range("C2").Value
        For Each rngCell In Intersect(Target, Range("A:A"))
            If Len(rngCell.Value) > 0 Then
                If InStr(1, rngCell.Value, strPrefix, vbTextCompare) <> 1 Then
                    rngCell.Value = strPrefix & rngCell.Value
                End If
            End If
        Next rngCell
    End If

clean_up:
    Application.EnableEvents = True
   Exit Sub

Worksheet_Change_Error:

    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Worksheet_Change of VBA Document Sheet1"
    Resume clean_up
End Sub
Random Solutions  
 
programming4us programming4us