Search code examples
vbams-accesserror-handling

Access VBA: Is it possible to reset error handling?


I am using in the first part of my program

On Error GoTo start

Suppose in my second part I am again using

On Error Resume Next

This second error trap will not get activated as the first one will still be active. Is there any way to de-activate the first error handler after it has been used?

Set objexcel = CreateObject("excel.Application")
                     objexcel.Visible = True
                     On Error GoTo Openwb
                     wbExists = False
                     Set wbexcel = objexcel.Workbooks.Open("C:\REPORT3.xls")
                     Set objSht = wbexcel.Worksheets("Sheet1")
                     objSht.Activate
                     wbExists = True
Openwb:
                     
                     On Error GoTo 0
                     If Not wbExists Then
                     objexcel.Workbooks.Add
                     Set wbexcel = objexcel.ActiveWorkbook
                     Set objSht = wbexcel.Worksheets("Sheet1")

                     End If
                     
                     On Error GoTo 0
                                         
Set db = DBEngine.opendatabase("C:\book.mdb")
Set rs = db.OpenRecordset("records")

Set rs2 = CreateObject("ADODB.Recordset")
rs2.ActiveConnection = CurrentProject.Connection


For Each tdf In CurrentDb.TableDefs
   
   If Left(tdf.Name, 4) <> "MSys" Then
        rs.MoveFirst
        strsql = "SELECT * From [" & tdf.Name & "] WHERE s=15 "

        Do While Not rs.EOF
            On Error Resume Next
            
            rs2.Open strsql 

Upon execution of the last statement I want to ignore the error and move on to the next table but error handling does not seem to work.


Solution

  • It is nearly always better to avoid errors, rather than handling them. For example:

    Set objexcel = CreateObject("excel.Application")
    objexcel.Visible = True
    
    'On Error GoTo Openwb '
    'wbExists = False '
    
    If Dir("C:\REPORT3.xls") = "" Then
        objexcel.Workbooks.Add
        Set wbexcel = objexcel.ActiveWorkbook
        Set objSht = wbexcel.Worksheets("Sheet1")
    Else
        Set wbexcel = objexcel.Workbooks.Open("C:\REPORT3.xls")
        Set objSht = wbexcel.Worksheets("Sheet1")
    End If
    
    objSht.Activate
    'wbExists = True '