1

我有以下 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

但是,如果我将 aExit Sub作为最后一条语句插入,If Shell(...) <> 0 Then则不会发现任何错误。

有人可以向我解释错误是什么以及为什么会抛出它吗?

4

1 回答 1

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
于 2012-10-31T17:20:49.077 回答