How to check if a file has already been opened by another user

Article contributed by Jonathan West

The following function will return True if a file is already in use by another user, and False if it is available for use.

The function is useful if you are running a macro on a set of files, and want to avoid having it stop with the dialog asking if you want to open a copy of the file

Function FileLocked(strFileName As String) As Boolean

On Error Resume Next

' If the file is already opened by another process,
' and the specified type of access is not allowed,
' the Open operation fails and an error occurs.
Open strFileName For Binary Access Read Lock Read As #1
Close #1

' If an error occurs, the document is currently open.
If Err.Number <> 0 Then
    FileLocked = True
    Err.Clear
End If

End Function

You could call it like this:

Sub Test()

If Not FileLocked("C:\Temp\Temp.doc") Then
    Documents.Open "C:\Temp\Temp.doc"
End If

End Sub


Click to view Terms of Use page

Click to view Disclaimer page