Sunday, November 6, 2016

Check whether an Excel File is Open on a Network

This function is useful if you want to see if someone else on a network has the file open

Private Declare Function lOpen Lib "kernel32" Alias "_lopen" (ByVal lpPathName As String, ByVal iReadWrite As Long) As Long
Private Declare Function lClose Lib "kernel32" Alias "_lclose" (ByVal hFile As Long) As Long

private const OF_SHARE_EXCLUSIVE=&H10

Private Function IsFileAlreadyOpen(FileName As String) As Boolean
    Dim hFile As Long
    Dim lastErr As Long
    hFile = -1
    lastErr = 0
    'hFile = lOpen(FileName, &H10)
hFile = lOpen(FileName, OF_SHARE_EXCLUSIVE)
    If hFile = -1 Then
        lastErr = Err.LastDllError
    Else
        lClose (hFile)
    End If
    sFileAlreadyOpen = (hFile = -1) And (lastErr = 32)
End Function
Private Sub Form_Load()
    MsgBox IsFileAlreadyOpen("c:\autoexec.bat")
End Sub


Private Sub CheckFileOpen()
if IsFileAlreadyOpen("C:\XYZ Corp.xlsx") then
MsgBox "File is open"
else
MsgBox "File is not open?


No comments: