Richard Schollar
MrExcel MVP
- Joined
- Apr 19, 2005
- Messages
- 23,707
I use this code to test for files already opened by another user or process:
Works fine. However, if I have a text file open within Notepad (haven't tested with other programs) on my computer (haven't tested if it behaves the same way when another user has the file open in Notepad) and execute the function, the function returns False (ie suggesting file isn't open). This line executes successfully:
I tested with this code with and without the target file being opened:
Firstly, can someone else confirm whether this is the case for them, and secondly explain why this is the case - I would have thought the Open statement should produce an error (and thus the function to return True). Or does Notepad specifically not Lock the file it has opened? Or some other reason?
Thanks for any and all replies!
Code:
Function IsFileOpen(strFile As String) As Boolean
Dim i As Integer
i = FreeFile
If Dir(strFile) = "" Then IsFileOpen = False: Exit Function
Err = 0
On Error Resume Next
Open strFile For Binary Access Read Lock Read Write As #i
If Err Then IsFileOpen = True
Close #i
End Function
Works fine. However, if I have a text file open within Notepad (haven't tested with other programs) on my computer (haven't tested if it behaves the same way when another user has the file open in Notepad) and execute the function, the function returns False (ie suggesting file isn't open). This line executes successfully:
Code:
Open strFile For Binary Access Read Lock Read Write As #i
I tested with this code with and without the target file being opened:
Code:
Sub test()
MsgBox IsFileOpen("C:\Test\Test.txt")
End Sub
Firstly, can someone else confirm whether this is the case for them, and secondly explain why this is the case - I would have thought the Open statement should produce an error (and thus the function to return True). Or does Notepad specifically not Lock the file it has opened? Or some other reason?
Thanks for any and all replies!