View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Mike H Mike H is offline
external usenet poster
 
Posts: 11,501
Default What is the test for whether a file is open?

Jim,

So what expression should "IsOpen(H)" be?


There isn't one you have to do it with code. heres a function you can caal
from your code and ive included a sample sub to text it. basically the
function opens and close the file and sees if an error occurs. No error, file
isn't open, error 70, file open.


Sub TestFileOpened()
If IsOpen("c:\Book2.xls") Then
MsgBox "File Open"
Else
MsgBox "File not open"
End If
End Sub

Function IsOpen(filename As String)
Dim filenum As Integer, errnum As Integer
On Error Resume Next
filenum = FreeFile()
Open filename For Input Lock Read As #filenum
Close filenum
errnum = Err
On Error GoTo 0
Select Case errnum
' NOT open.
Case 0
IsFileOpen = False
' File open
Case 70
IsFileOpen = True
End Select
End Function

Mike

"Jim Luedke" wrote:

What's the test for whether a file is currently open (or closed)?

My app writes to a log file, but I don't want to burden the caller
with opening the file in the event he never has to write to it. So I
want:

Dim H As Long

Sub Log(Msg as String)
If Not IsOpen(H) then
Open LogFile For Output As #H
Print #H, FileHeader & DateTime
Print #H,
End If

Print #H, Msg
End Sub

Sub Main
Repeat
If Not Something Then
Log "Oops"
End If
Until SomethingElse
Close #H
End Sub

So what expression should "IsOpen(H)" be?

Thanks.

***