简体   繁体   中英

Why do some VBA errors not trigger error handling?

Whilst updating my code this morning, I caused an error - I replaced a function with a string but forgot to take out the parenthesese that followed, which caused the code not to run.

However, this didn't trigger my error handling code, so it didn't report the error and it took me ages to find it by stepping through the code.

Code below:

Private Sub Form_Close()

On Error GoTo ErrHandler

'Update to say the user is no longer logged in

        DoCmd.SetWarnings False
        DoCmd.OpenQuery "Last Logged Out"

'Backup data
If (strNameChecker <> "workshop.accdb") Then

        strBackupUser = Nz(GetFullName(), "default")
        strFriendlyNow = Replace(Now(), "/", "-")
        strFriendlyNow = Replace(strFriendlyNow, ":", "-")
        strNewFileName = "F:\Data\Central\Marketing\Databases\Prospects Database\Auto-Backups\TargetDBData - backed up by " & strBackupUser() & " on " & strFriendlyNow & ".mdb"
        BackupProspects "F:\Data\Central\Marketing\Databases\Prospects Database\TargetDBData.mdb", "" & strNewFileName & ""
        sSql = "INSERT INTO [Backup to Delete] ([Version Number]) SELECT '" & strNewFileName & "' AS Expr1;"
        DoCmd.RunSQL sSql


'Delete the temporary version of the front end.
        DoCmd.OpenQuery "Update - Version Shutdown"
        DoCmd.SetWarnings True
        Application.FollowHyperlink "F:\Data\Central\Marketing\Databases\Prospects Database\Prospects Database Shutdown.accdb"

End If

Exit Sub

ErrHandler:
DoCmd.SetWarnings True
MsgBox "The database has generated an error. Please contact the database administrator, quoting the following error message: '" & Err.Description & "'", vbCritical, "Database Error"

End Sub

The error is caused by the two parenthese after strBackupUser about halfway down the code - delete these and the code works fine - but why doesn't this error trigger the error handling?

You don't appear to have Option Explicit at the top of your module. As a result, all the string variables will be silently declared as Variant . I'm not sure what the compiler will make of the expression strBackupUser() , I guess it will attempt some kind of horrible late-bound object or array access.

I suggest that you add Option Explicit first, then explicitly declare all your variables as strings, then see whether you get a compiler error.

Here is a useful "war story" that illustrates how and why to use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM