PDA

View Full Version : test if text file is open



Djblois
12-11-2007, 01:11 PM
I use a text file in my program to create a logfile as the program runs to help me debug it. However, sometimes it is left open and then when it tries to reopen it crashes. Here is the code that I use to open it:

Dim logFile As String

logFile = "H:\@Temp\Daniel B\Log Files\" & Environ("UserName") & "_LogFile.txt"

FileNumber = FreeFile ' Get unused fileno
'Create file name.
Open logFile For Append As #FileNumber

How can I test to see if it is open first? I know how to do it with a word file and an excel file but I tried to figure that out but it is completely different.

carlmack
12-11-2007, 02:31 PM
One possiblity would be to check if it errors and report it. Maybe a function like



Private Function IsFileOK(FullPath As String) As Boolean
Dim f As Integer
IsFileOK = True
On Error GoTo FileProblem
f = FreeFile
Open FullPath For Append As #f
Close #f
Exit Function
FileProblem:
IsFileOK = False
End Function


used like


If IsFileOK(logfile) Then
filenumber = FreeFile
Open logfile For Append As #filenumber
' ...
Close #filenumber
Else
MsgBox ("Can not access file")
End If