Dear Experts,
I copied the following code from MSDN, I suppose that On Error GoTo will avoid run-time error message box show up. But when I try to run the following code in debug mode line by line, run-time error message box still poped up, why? If error occurs in line 'Kill "myfile.txt"', why it didn't go to ErrorHandler?
Please help!
Option Explicit
Private Sub Command1_Click()
OnErrorStatementDemo
End Sub
Sub OnErrorStatementDemo()
Dim ObjectRef
Dim Msg As String
On Error GoTo ErrorHandler
Open "myfile.txt" For Output As #1
Kill "myfile.txt"
On Error GoTo 0
On Error Resume Next ' Defer error trapping.
ObjectRef = GetObject("MyWord.Basic") ' Try to start nonexistent
' object, then test for
'Check for likely Automation errors.
If Err.Number = 440 Or Err.Number = 432 Then
' Tell user what happened. Then clear the Err object.
Msg = "There was an error attempting to open the Automation object!"
MsgBox Msg, , "Deferred Error Test"
Err.Clear ' Clear Err object fields
End If
Exit Sub ' Exit to avoid handler.
ErrorHandler: ' Error-handling routine.
Select Case Err.Number ' Evaluate error number.
Case 55 ' "File already open" error.
Close #1 ' Close open file.
Case Else
' Handle other situations here...
End Select
Resume ' Resume execution at same line
' that caused the error.
End Sub
If the error occurred in the sameprocedure as the error handler, execution resumes with the statement that caused the error. If the error occurred in a called procedure, execution resumes at thestatement that last called out of the procedure containing the error-handling routine.
So if the file doesn't exist in the first place you aren't capturing that error and are just returning without fixing it thus causing the error to occur again.