我正在尝试创建一个“库”,用于显示弹出的错误,以便使用我的电子表格的人立即知道出了什么问题。这对于标准错误很有效,但我无法让它在运行时错误上触发。在这种情况下,运行时错误 53 正在发生,我认为是因为它试图删除未成功保存的临时文件(这是我的消息框将显示的内容)。
注意 - 我并不是想解决这个错误,我故意让它跳出来,以便用户知道出了什么问题。我只是想让给定的消息框在运行时错误 53 发生时出现。
因此这个宏有效,因为它只是一个标准的 1004 错误:
Sub ReportSaveandEmail()
Dim IsCreated As Boolean
Dim i As Long
Dim PdfFile As String, Title As String
Dim OutlApp As Object
On Error GoTo Whoa
'-> Sub deleted
Whoa:
Dim OutPut As Integer
Select Case Err.Number
Case 1004 'Search error'
OutPut = MsgBox("Found an error (#1004). This error usually occurs when the macro is searching for a file or folder that doesn't exist. Please check your code.", vbCritical, "File not found")
End Select
End Sub
但这个运行时错误并没有触发。我只收到一个标准的 Excel 消息框:“Micosoft Visual Basic | 运行时错误 53 | 未找到文件”
Sub ReportSaveandEmail()
Dim IsCreated As Boolean
Dim i As Long
Dim PdfFile As String, Title As String
Dim OutlApp As Object
On Error GoTo Whoa
'-> Sub deleted
Whoa:
Dim OutPut As Integer
Select Case Err.Number
Case 53 'Can't find file to delete'
OutPut = MsgBox("Found an error (#53). This error usually occurs when the macro tries to delete a temporary file that was not successfully created.", vbCritical, "Temp File not found")
End Select
End Sub
谢谢!
答案1
您的代码不完整,它没有显示您如何设置错误。
故意引发错误 53 似乎可以正常工作。
Sub ReportSaveandEmail()
On Error GoTo Whoa
Err.Raise 1004
Err.Raise 53
Exit Sub
Whoa:
Select Case Err.number
Case 1004 'Search error'
MsgBox "Found an error (#1004). This error usually occurs when the macro is searching for a file or folder that doesn't exist. Please check your code.", vbCritical, "File not found"
Resume Next
Case 53 'Can't find file to delete'
MsgBox "Found an error (#53). This error usually occurs when the macro tries to delete a temporary file that was not successfully created.", vbCritical, "Temp File not found"
Resume Next
End Select
End Sub
请注意,一旦您提高 1004,您就必须清除或恢复以允许 53 被困。