MS Access / VBA:将条件添加到vba代码

时间:2016-01-27 15:58:31

标签: vba ms-access access-vba ms-access-2013

我有以下代码:

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

问题是如果“Table1”不存在,我会收到VBA / debug错误。我是否可以添加一些条件,如果脚本找不到“Table1”,它应该更进一步删除其他2个表而不返回任何错误消息?

3 个答案:

答案 0 :(得分:4)

你的意思是错误捕获?以下是一个如何捕获"陷阱的例子。错误 - 如果尝试删除Table1时发生错误,它会询问您是否要继续:

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

答案 1 :(得分:2)

如果您决定陷阱并忽略该错误,请首先忽略错误7874( Microsoft Access无法找到对象'。)您可能不愿意忽略其他错误,例如表正在使用时。

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

注意:

  • 如果您发现了您希望忽略的其他错误,可以将这些错误编号添加到第一个Case语句中:Case 7874, <another number here>
  • 我认为没有理由在此程序中关闭SetWarnings
  • 在尝试删除表之前,请考虑Alex的suggestion来检查表是否存在。

答案 2 :(得分:-1)

好吧,如果你想删除只存在于Access中的表,那么你可以简单地检查一下这个对象,以下是你通常的做法:

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