简体   繁体   English

为什么有些VBA错误不会触发错误处理?

[英]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? 错误是由strBackupUser在代码中途的两个括号引起的 - 删除这些并且代码工作正常 - 但为什么这个错误不会触发错误处理?

You don't appear to have Option Explicit at the top of your module. 您似乎没有在模块顶部显示Option Explicit As a result, all the string variables will be silently declared as Variant . 因此,所有字符串变量都将以静默方式声明为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. 我不确定编译器将对表达式strBackupUser()做什么,我猜它会尝试某种可怕的后期绑定对象或数组访问。

I suggest that you add Option Explicit first, then explicitly declare all your variables as strings, then see whether you get a compiler error. 我建议您先添加Option Explicit ,然后将所有变量显式声明为字符串,然后查看是否出现编译器错误。

Here is a useful "war story" that illustrates how and why to use it. 这是一个有用的“战争故事” ,说明了如何以及为何使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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