Reputation: 2308
I have a VBA code that creates a file and need to have an error handling routine in case something happens in which the file closes (If it is actually open at all).
If the file is open and crashes before it gets to Close #F, or even before it is actually created.
Sub test1()
On Error GoTo Err
Dim rs As DAO.Recordset
Dim F As Integer
F = FreeFile
Open "C:\MYFILE.TXT" For Output As #F
' My code that does lots of stuff...
If Not rs Is Nothing Then rs.Close
Close #F
Exit_Sub:
Set rs = Nothing
Exit Sub
Err:
MsgBox Err.Description
Resume Exit_Sub
End Sub
Upvotes: 1
Views: 3246
Reputation: 149305
Change this part
Exit_Sub:
Set rs = Nothing
Exit Sub
to
Exit_Sub:
On Error Resume Next
Close #F
On Error GoTo 0
Set rs = Nothing
Exit Sub
And remove the Close #F
from where it was earlier...
Upvotes: 3