Showing posts with label File not closed error in VBA. Show all posts
Showing posts with label File not closed error in VBA. Show all posts

Sunday, April 08, 2007

Run-time Error 55!!! File already open

Run-time Error 55 File already open. This is one of the common error in file handling. It is difficult to avoid if you handle multiple files and use direct file numbers


Sub TextFile_Write_Error()

' ---------------------------------------------------------------
' Written By Shanmuga Sundara Raman for http://vbadud.blogspot.com
' ---------------------------------------------------------------
'


' ------------------------
' Code with Errors
' ------------------------
Open "d:\VBADudExamples\TextFile1.txt" For Output As #1 ' Open file for output.

Print #1, "TextFile1"

Open "d:\VBADudExamples\TextFile2.txt" For Output As #1 ' Open file for output.

Close #1 ' Close file.

Close #1 ' Close file.

' ------------------------
' Workaround for the Errors
' ------------------------
' Use FreeFile to get a file number that is not used

iF1 = FreeFile ' Returns an Integer representing the next file number available for use by the Open statement.
Open "d:\VBADudExamples\TextFile1.txt" For Output As #iF1 ' Open file for output.

Print #iF1, "TextFile1"

iF2 = FreeFile
Open "d:\VBADudExamples\TextFile2.txt" For Output As #iF2 ' Open file for output.

Close #iF2 ' Close file.

Close #iF1 ' Close file.


' ------------------------------------------------
' Excel VBA, Run-time Error 55, File already open
' ------------------------------------------------


End Sub
Related Posts Plugin for WordPress, Blogger...
Download Windows Live Toolbar and personalize your Web experience! Add custom buttons to get the information you care about most.