I've been encountering a situation where a text file channel, according to VB, is already open. It occurs about 10% of the time the routine is called. This has given me a rather puzzling problem. How is it that a 'File already open' error can occur at line #112, given that the file channel would have just been closed??
The size of the files saved is rather small, about 1,000 characters. I've carefully checked through the code in my app:
(i) all references to files make use of the 'intfnum = FreeFile' method, ie, no fixed channel assignments
(ii) files are closed prior to the end of each subroutine
I searched EE and found a suggestion to introduce a small delay, hence the loop below. I'm not sure if this has made a difference.
Your help in advance is most appreciated.
Private Function DO_THE_FILE_SAVE(ByVal FilePath As String, ByVal s As String)
'11-oct-07, bring it here
Dim intfnum As Integer, FileChannelNumber As Integer
Dim Result As Long, j As Long
Const procname As String = "DO_THE_FILE_SAVE"
On Error GoTo Err
100 If IsFileAlreadyOpen(FilePath, s, FileChannelNumber) = -1 Then
Close #FileChannelNumber 'if the file happens to still be open from a previous operation, close it
104 For j = 1 To 40000 'delay, typically a few hundred milliseconds, so we can try again
110 intfnum = FreeFile 'a new file handle
112 Open FilePath For Output As #intfnum
114 Print #intfnum, s
116 Close #intfnum
120 Exit Function
200 MsgBox "ErrCode: " & Erl & vbCrLf & "Error: " & Err.Description 'File already open' error
Private Function IsFileAlreadyOpen(ByVal FilePath As String, ByVal s As String, ByRef FileChannelNumber As Integer)
Dim intfnum As Integer
Const procname As String = "IsFileAlreadyOpen"
On Error GoTo Err
100 intfnum = FreeFile
Open FilePath For Input As #intfnum
IsFileAlreadyOpen = 0 'ie, ok
Select Case Err.number
Case 55 'thanks EE
IsFileAlreadyOpen = -1 'error
FileChannelNumber = intfnum