Word

Check if file is opened by another process

Ease of Use

Easy

Version tested with

2000, 2002 

Submitted by:

MOS MASTER

Description:

The function checks if a file is opened by another process and if the specified type of action (Opening) is allowed. 

Discussion:

Before you open a document it's always a good idea to check if it has been opened already. If you don't do that you get a error that the file is already opened! (Permission denied!) 

Code:

instructions for use

			

Option Explicit Sub OpenDocument() Dim sFileName As String ' \\ Full path of test file sFileName = ThisDocument.Path & "\Test.doc" ' \\ Only open File if the file is not opened yet If Not IsFileLocked(sFileName) Then Application.Documents.Open FileName:=sFileName End If End Sub ' \\ This function checks if the file is allready opened by another process, ' \\ and if the specified type of access is not allowed. ' \\ If so the Open method will fail and a error occurs! Function IsFileLocked(sFile As String) As Boolean On Error Resume Next ' \\ Open the file Open sFile For Binary Access Read Write Lock Read Write As #1 ' \\ Close the file Close #1 ' \\ If error occurs the document if open! If Err.Number <> 0 Then ' \\ msgbox for demonstration purposes MsgBox Err.Description, vbExclamation, "Warning File is opened" '\\ Return true and clear error IsFileLocked = True Err.Clear End If End Function

How to use:

  1. Open your Word document.
  2. Press Alt + F11 to open VBE.
  3. Insert-Module. (Insert -> module)
  4. Paste the code there in the window at right. (F7)
  5. Close VBE (Alt + Q or press the X in the top right hand corner).
  6. Save the file.
 

Test the code:

  1. Open the document.
  2. Press ALT+F8 and choose OpenDocument. (The test file will open)
  3. Leave the test file open and run the macro again a msgbox is show.
 

Sample File:

FileLocked.zip 9.76KB 

Approved by mdmackillop


This entry has been viewed 77 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express