我有以下Excel VBA函数来打开日志文件以供查看,它可以正确执行所有操作,但在关闭文件后它始终会抛出错误:
Private Sub ViewLog_Click()
On Error GoTo LogFileOpenHandler:
If Shell("notepad.exe " & LOG_FULL_FILENAME, vbMaximizedFocus) <> 0 Then
' Log file opened successfully
MsgBox "log file opened"
Else
MsgBox "Oopsies! Could not open log file for viewing."
End If
LogFileOpenHandler:
MsgBox "Oops...Unknown error occured. Could not open log file for viewing."
On Error GoTo 0
End Sub
但是,如果我在Exit Sub
中插入If Shell(...) <> 0 Then
作为最后一个语句,则不会发现错误。
有人可以向我解释错误是什么以及为什么会抛出错误?
答案 0 :(得分:2)
它表示存在错误的原因是因为您在Exit Sub
阻止后没有If
(就像您提到的那样)。因此,每次运行程序时,它都会一直运行并在LogFileOpenHandler:
下生成消息框,因为没有什么可以阻止代码执行该脚本。
如果您重新添加Exit Sub
,它将按您的要求运行:
Private Sub ViewLog_Click()
On Error GoTo LogFileOpenHandler:
If Shell("notepad.exe " & LOG_FULL_FILENAME, vbMaximizedFocus) <> 0 Then
' Log file opened successfully
MsgBox "log file opened"
Else
MsgBox "Oopsies! Could not open log file for viewing."
End If
Exit Sub
LogFileOpenHandler:
MsgBox "Oops...Unknown error occured. Could not open log file for viewing."
On Error GoTo 0
End Sub