2012-05-14 54 views
1

我有一個VBA代碼創建一個文件,並且需要有一個錯誤處理例程,以防文件關閉時發生什麼事情(如果它實際上是打開的話)。VBA:在關閉文件上的錯誤處理

如果文件在打開並崩潰之前到達關閉#F,或甚至在它實際創建之前。

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 

回答

3

更改這一部分

Exit_Sub: 
    Set rs = Nothing 
    Exit Sub 

Exit_Sub: 
    On Error Resume Next 
    Close #F 
    On Error GoTo 0 
    Set rs = Nothing 
    Exit Sub 

並從它前面是Close #F ...