Function IsWorkbookOpen(sFilePathName As String) As Variant
'20160720 Update
'IsWorkbookOpen is returned as {x,y}
'X is True if file is open or False if it is closed
'If it is a workbook and open, Y will be the username
'If it is not a workbook and open, Y will be "Not Workbook"
'If file does not exist X will be False, Y will be "Does Not Exist"
'KEYWORDS: Is File Open, Is Workbook Open
Dim fso As Object, bFE As Boolean
Dim wbk As Workbook
Dim sExt As String
Dim iFilenum As Integer, lErrnum As Long
Dim sFileNameExt As String
Dim secAutomation As MsoAutomationSecurity
secAutomation = Application.AutomationSecurity 'Save ThisWorkbook security setting
Application.AutomationSecurity = msoAutomationSecurityForceDisable 'Disable macros when opening file
Set fso = CreateObject("Scripting.FileSystemObject")
bFE = fso.FileExists(sFilePathName)
sExt = fso.GetExtensionName(sFilePathName)
sFileNameExt = fso.GetFilename(sFilePathName)
If bFE Then
'File Exists
'Is it a workbook
If InStr(".xls..xlsm..xlsx..xlsb..xla..xlam..", sExt) = 0 Then
'Not a workbook
On Error Resume Next ' Turn error checking off.
iFilenum = FreeFile() ' Get a free file number.
' Attempt to open the file and lock it.
Open sFilePathName For Input Lock Read As #iFilenum
Close iFilenum ' Close the file.
lErrnum = Err ' Save the error number that occurred.
On Error GoTo 0 ' Turn error checking back on.
' Check to see which error occurred.
Select Case lErrnum
Case 0 ' File is NOT already open
IsWorkbookOpen = Array(False, "Not Workbook")
Case 70 'Permission Denied.
IsWorkbookOpen = Array(True, "Not Workbook")
Case Else 'Other error
'Something else, Display Error
Error lErrnum
End Select
GoTo End_Function
End If
'Is it a workbook opened in this instance of Excel?
ThisWorkbook.Activate 'if another instance of Excel is active this check may fail
For Each wbk In Application.Workbooks
If wbk.Name = sFileNameExt Then
IsWorkbookOpen = Array(True, Application.UserName) 'Workbook Open being used by ....
GoTo End_Function
End If
Next
'Check to see if workbook is already open in another instance of Excel...by trying to open it
Set wbk = Workbooks.Open(sFilePathName)
If wbk.ReadOnly Then
IsWorkbookOpen = Array(True, wbk.WriteReservedBy) 'Workbook Open being used by ....
Workbooks(sFileNameExt).Close SaveChanges:=False 'Close the read only copy we just opened
'MsgBox wbk.WriteReservedBy & " currently using " & wbk.Name
GoTo End_Function
Else
'Workbook was not open
IsWorkbookOpen = Array(False, True) 'Not Open, is a workbook
'Was opened by this procedure -- now close it
Workbooks(sFileNameExt).Close SaveChanges:=False
End If
Else
IsWorkbookOpen = Array(False, "Does Not Exist") 'File does not exist it cannot be open
End If
End_Function:
Set fso = Nothing
Application.AutomationSecurity = secAutomation 'Restore ThisWorkbook security setting
End Function