Currentdb.Execute with dbFailonError not throwing an error

久未见 提交于 2020-12-13 17:56:39

问题


In Access 2003-2016, I am using CurrentDb.Execute with dbFailonError to run an INSERT statement. The INSERT statement should fail (and it does) because one field has an incorrect value based on a related table with "Enforced Referential Integrity". However, it does not throw an error. I have tried recreating this issue in a new database, and the error works correctly. There is something wrong in the settings with my current database, and I don't want to recreate it from scratch. I have taken everything out of my database except for the problematic piece, and my minimal reproducible example database is at this link.

Here is my code, but the problem is that this code works fine and does throw errors when I create a new database from scratch. It just doesn't work in my current database.

Private Sub Command34_Click()
    Dim testsql As String

    testsql = "INSERT INTO tblObservations (Site,TotalDepth) VALUES ('SUD-096',5)"
    With CurrentDb
        On Error GoTo Err_Execute
        .Execute testsql, dbFailOnError
        On Error GoTo 0
        MsgBox ("Upload completed.  " & .RecordsAffected & " records added.")
    End With
    Exit Sub
    
Finish:
    Exit Sub
    
Err_Execute:
    If DBEngine.Errors.Count > 0 Then
        For Each errLoop In DBEngine.Errors
            MsgBox ("Error number: " & errLoop.Number & vbCr & errLoop.Description)
        Next errLoop
    End If
    Resume Finish

End Sub

回答1:


Use Option Explicit, like Hans said. Always use Option Explicit!

You're missing a reference to the Microsoft Office ##.# Access Database Engine object. This is where dbFailOnError is defined. Because you don't have that reference, dbFailOnError is not defined. This reference is added to all Access databases by default, and I strongly recommend adding it.

And because you're not using Option Explicit, VBA doesn't mind that it's undefined and just casts that undefined variable to a zero.

If, for some reason, you don't want to add the reference, use the corresponding value for dbFailOnError:

.Execute testsql, 128


来源:https://stackoverflow.com/questions/64216792/currentdb-execute-with-dbfailonerror-not-throwing-an-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!