2

I have the following code :

Private Sub Command66_Click()
DoCmd.SetWarnings False
DoCmd.DeleteObject acTable, "Table1"
DoCmd.DeleteObject acTable, "Table2"
DoCmd.DeleteObject acTable, "Table3"
DoCmd.SetWarnings True
End Sub

The problem is that if "Table1" is not present,I receive an VBA/debug Error. Can I add some condition that if the script doesn't find "Table1" it should go further and delete the other 2 tables without returning any error message?

HansUp
  • 95,961
  • 11
  • 77
  • 135
adp
  • 311
  • 2
  • 7
  • 19
  • 2
    See if it exists first: [how to check if table is exists or not in ms access for vb macros?](http://stackoverflow.com/questions/3350645/how-to-check-if-table-is-exists-or-not-in-ms-access-for-vb-macros) – Alex K. Jan 27 '16 at 16:06

3 Answers3

4

You mean error trapping? Here's an example of how you can "trap" an error - If an error occured trying to delete Table1 it will ask you if you want to continue:

Private Sub Command66_Click()
DoCmd.SetWarnings False

On Error Resume Next
DoCmd.DeleteObject acTable, "Table1"

If Err.Number > 0 Then
    Err.Clear
    On Error GoTo 0
    If MsgBox("There was an error trying to delete Table1, do you want to continue?", vbYesNo) = vbYes Then
        DoCmd.DeleteObject acTable, "Table2"
        DoCmd.DeleteObject acTable, "Table3"
    End If
End If
DoCmd.SetWarnings True
End Sub
SierraOscar
  • 17,507
  • 6
  • 40
  • 68
2

If you decide to trap and ignore the error, start by ignoring only error 7874 (Microsoft Access can't find the object ''.) You may prefer not to ignore other errors, such as when the table is in use.

Private Sub Command66_Click()

    Dim strMsg As String

On Error GoTo ErrorHandler

    DoCmd.DeleteObject acTable, "Table1"
    DoCmd.DeleteObject acTable, "Table2"
    DoCmd.DeleteObject acTable, "Table3"

ExitHere:
    Exit Sub

ErrorHandler:
    Select Case Err.Number
    Case 7874 'Microsoft Access can't find the object
        Resume Next
    Case Else
        strMsg = "Error " & Err.Number & " (" & Err.Description _
            & ") in procedure Command66_Click"
        MsgBox strMsg
        GoTo ExitHere
    End Select
End Sub

Notes:

  • If you discover other errors you wish to ignore, you can add those error numbers to the first Case statement: Case 7874, <another number here>
  • I don't see any reason to turn SetWarnings off in this procedure.
  • Consider Alex's suggestion to check whether the table exists before attempting to delete it.
Community
  • 1
  • 1
HansUp
  • 95,961
  • 11
  • 77
  • 135
-1

Well, if you want to delete table that only exists in Access then you can simply check for the object, here is how you normally do it:

On Error Resume Next
If IsObject(CurrentDb.TableDefs("Table1")) Then
    DoCmd.DeleteObject acTable, "Table1"
End If
Arctics
  • 1
  • 1