Page 1 of 1

[Solved] Macro to check if a file is open or locked

Posted: Mon Jan 17, 2011 4:12 pm
by ttt_1978
I'm looking for a code to check if a OOo Calc or OOo Writer File is open.
In VBA I used the function below:

Code: Select all

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 Write Lock Read Write As #1
   Close #1
   ' If an error occurs, the document is currently open.
   If Err.Number <> 0 Then
      ' Display the error number and description.
      FileLocked = True
      Err.Clear
   End If
End Function
If the file was open by another user, the FileLocked Function returned True.
But it doesn't work for Ooo Files.
Can anyone help me?

Re: Macro to check if a file is open or locked

Posted: Mon Jan 17, 2011 4:53 pm
by RoryOF
You could look for the file lock, which is a short length file, with name of form .~lock.(file name)#

Re: Macro to check if a file is open or locked

Posted: Mon Jan 17, 2011 5:51 pm
by ttt_1978
Hhmmm, not all the Ooo Files generates a .~lock.(file name)# when accessed.
I did some tests in our shared documents at my work and those files never appear in the container folder.

Re: Macro to check if a file is open or locked

Posted: Mon Jan 17, 2011 6:36 pm
by ttt_1978
RoryOF,
I realized that the .~lock.(file name) is a hidden file.
I will write a code that search for this file.

[SOLVED] Macro to check if a file is open or locked

Posted: Mon Jan 17, 2011 7:20 pm
by ttt_1978
RoryOF,

Thank you. It works.

My code:

Code: Select all

Sub CheckIfFileIsLocked()
Dim StrPath, StrFile, StrFileLocked As String
StrPath = "C:/"
StrFile = "Test.odt"
StrFileLocked  = StrPath & ".~lock." & StrFile & "#"
If FileExists(StrFileLocked) Then 
  MsgBox "File locked for editing by another user. Try again later.", 16
  Exit Sub
End If
End Sub
Or

Code: Select all

Function FileLocked(StrPath As String, StrFile As String) As Boolean
Dim StrFileLocked As String
StrFileLocked  = StrPath & ".~lock." & StrFile & "#"
If FileExists(StrFileLocked) Then 
   FileLocked = True
Else
   FileLocked = False
End If
End Function

Re: [SOLVED] Macro to check if a file is open or locked

Posted: Mon Jan 17, 2011 7:30 pm
by ttt_1978
If anyone has another method, it is wellcomed.