3

今天早上更新我的代码时,我导致了一个错误 - 我用一个字符串替换了一个函数,但忘记取出后面的括号,这导致代码无法运行。

但是,这并没有触发我的错误处理代码,所以它没有报告错误,我花了很长时间才通过单步执行代码找到它。

下面的代码:

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

该错误是由 strBackupUser 之后的两个括号引起的,大约在代码的一半 - 删除它们并且代码工作正常 - 但是为什么这个错误不会触发错误处理?

4

1 回答 1

5

Option Explicit您的模块顶部似乎没有。结果,所有字符串变量都将被静默声明为Variant. 我不确定编译器会对表达式做什么strBackupUser(),我猜它会尝试某种可怕的后期绑定对象或数组访问。

我建议您Option Explicit先添加,然后将所有变量显式声明为字符串,然后查看是否出现编译器错误。

这是一个有用的“战争故事”,说明了如何以及为什么要使用它。

于 2012-07-27T12:04:47.213 回答