81

In VBA, I opened an MS Excel file named "myWork.XL" programmatically.

Now I would like a code that can tell me about its status - whether it is open or not. I.e. something like IsWorkBookOpened("myWork.XL) ?

Andrei Konstantinov
  • 6,971
  • 4
  • 41
  • 57
user1222679
  • 923
  • 2
  • 9
  • 6

7 Answers7

104

Try this:

Option Explicit

Sub Sample()
    Dim Ret

    Ret = IsWorkBookOpen("C:\myWork.xlsx")

    If Ret = True Then
        MsgBox "File is open"
    Else
        MsgBox "File is Closed"
    End If
End Sub

Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0:    IsWorkBookOpen = False
    Case 70:   IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function
Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
  • 2
    +1 I've used this method for sometime to check files on a newtwork drive accessible by other users. I think the code was originally posted on a msft site. – brettdj Feb 21 '12 at 09:28
  • 5
    Personally I would feel very uncomfortable using primitive file IO to attempt a file read on an open Excel workbook when IMHO there are better alternatives: but maybe it works? – Charles Williams Feb 21 '12 at 20:34
  • 3
    @Charles Williams: Yes, it may be primitive but it is still a good code with no disadvantages. At least none that I know of. :) Try it maybe you will like it? – Siddharth Rout Feb 22 '12 at 01:43
  • I am sure it works, but what do you see as the disadvantages of the simpler more Excel-friendly code? (opening the workbook using Workbooks.Open and checking Workbook.Readonly) – Charles Williams Feb 22 '12 at 08:52
  • 6
    @CharlesWilliams Fair point. Although in my case when I tried something similar the time overhead of actually *opening* a large model hosted on a overseas server was around 2-3 minutes. Which gave a "grrr" moment when it opened readonly, whereas Sid's function above gave an immediate response. FWIW Bob Phillips listed a similar function at [vbaexpress](http://www.vbaexpress.com/kb/getarticle.php?kb_id=468) , a more advanced version waiting for the book to be closed elsewhere from [Chip Pearson](http://www.cpearson.com/excel/WaitForFileClose.htm) – brettdj Mar 10 '12 at 06:50
  • @SiddharthRout There is one disadvantage that just bit me. I just tested that above code when saved as "C:\myWork.xlsm", closed, then opened as _read-only_ and run will pop MsgBox "File is Closed". This is incorrect since ThisWorkbook is open and running Sample(). Seems like fix is to include code that also checks each Application.Workbooks().name – Chuck The Nerd Mar 21 '14 at 21:15
  • @SiddharthRout - have you tried GetObject( [MyfilePath], Class:="Excel.Workbook" ) ? This seems to work, and I've tested it with multiple instances of Excel.exe - however, I can think of several failure modes and I'm reluctant to post an answer without a *lot* more testing. – Nigel Heffernan Jul 27 '15 at 09:48
  • @Nile: If you can think of several failure modes then it is not a reliable solution :) – Siddharth Rout Jul 27 '15 at 09:52
  • Doesn't work I'm afraid. I've copy pasted it verbatim. Which version of VBA is this? – AER Aug 18 '16 at 07:35
  • @AER: It worked then and it works now as well :) Are you sure you are passing the correct file path and name? – Siddharth Rout Aug 18 '16 at 10:50
  • @SiddharthRout: Hmm, OK. Yes, I both copy-pasted and typed it in. Does it require any admin rights? – AER Aug 19 '16 at 04:33
  • It seems like IsWorkBookOpen() will go to Case 0 (IsWorkBookOpen = False) on a shared workbook whether the workbook is open or closed. – Kirk Kittell Jun 22 '18 at 17:14
59

For my applications, I generally want to work with a workbook rather than just determine if it's open. For that case, I prefer to skip the Boolean function and just return the workbook.

Sub test()

    Dim wb As Workbook

    Set wb = GetWorkbook("C:\Users\dick\Dropbox\Excel\Hoops.xls")

    If Not wb Is Nothing Then
        Debug.Print wb.Name
    End If

End Sub

Public Function GetWorkbook(ByVal sFullName As String) As Workbook

    Dim sFile As String
    Dim wbReturn As Workbook

    sFile = Dir(sFullName)

    On Error Resume Next
        Set wbReturn = Workbooks(sFile)

        If wbReturn Is Nothing Then
            Set wbReturn = Workbooks.Open(sFullName)
        End If
    On Error GoTo 0

    Set GetWorkbook = wbReturn

End Function
Dick Kusleika
  • 32,673
  • 4
  • 52
  • 73
  • 2
    I agree thats usually what is wanted: if you want to check for the book being already open in another Excel instance you can check if its been opened readonly – Charles Williams Feb 21 '12 at 20:30
  • This giveme out of bounds error on `Workbooks(sFile)` – motobói Jun 10 '14 at 16:01
  • 1
    You must not have `On Error Resume Next` in the code or you have Break on All Errors set under Tools - Options in the VBE. – Dick Kusleika Jun 10 '14 at 18:39
  • This version works better for me, the version above seems to not detect workbooks open in read only... – Lowpar Dec 05 '17 at 08:29
  • I used to use this, but these days I've been getting a lot of **Automation errors** in Excel 2017 when the concerned workbook had been closed moments prior to running the macro. The solution was to forgo `On Error Resume Next` (because `wbReturn` was ***not*** `Nothing`, but contained an error) and write real error handling. See: https://pastebin.com/u1LLgPa1 – André Chalella Dec 18 '17 at 00:09
  • This does not work if the workbook is open in another Excel instance! – feetwet Apr 15 '21 at 19:36
22

If its open it will be in the Workbooks collection:

Function BookOpen(strBookName As String) As Boolean
    Dim oBk As Workbook
    On Error Resume Next
    Set oBk = Workbooks(strBookName)
    On Error GoTo 0
    If oBk Is Nothing Then
        BookOpen = False
    Else
        BookOpen = True
    End If
End Function

Sub testbook()
    Dim strBookName As String
    strBookName = "myWork.xls"
    If BookOpen(strBookName) Then
        MsgBox strBookName & " is open", vbOKOnly + vbInformation
    Else
        MsgBox strBookName & " is NOT open", vbOKOnly + vbExclamation
    End If
End Sub
Charles Williams
  • 23,121
  • 5
  • 38
  • 38
  • 11
    Charles, I already thought of this method. The main drawback on this method is that if the workbook is opened in a different Excel instance then you will always get the value as false :) the alternative would be to add code to loop through all Excel instances and then use your code. Ultimately I realized that I was writing more code and hence I used an alternative approach. Sid – Siddharth Rout Feb 21 '12 at 09:04
  • 4
    If you want to check for the book being open in another Excel instance (presumably because you won't be able to save it or edit it) why not just check if its Readonly after opening it (If oBk.Readonly ...) – Charles Williams Feb 21 '12 at 20:29
14

I would go with this:

Public Function FileInUse(sFileName) As Boolean
    On Error Resume Next
    Open sFileName For Binary Access Read Lock Read As #1
    Close #1
    FileInUse = IIf(Err.Number > 0, True, False)
    On Error GoTo 0
End Function

as sFileName you have to provide direct path to the file for example:

Sub Test_Sub()
    myFilePath = "C:\Users\UserName\Desktop\example.xlsx"
    If FileInUse(myFilePath) Then
        MsgBox "File is Opened"
    Else
        MsgBox "File is Closed"
    End If
End Sub
user2267971
  • 373
  • 1
  • 4
  • 12
6

What if you want to check without creating another Excel instance?

For example, I have a Word macro (which is run repeatedly) that needs to extract data from an Excel spreadsheet. If the spreadsheet is already open in an existing Excel instance, I would prefer not to create a new instance.

I found a great answer here that I built on: http://www.dbforums.com/microsoft-access/1022678-how-check-wether-excel-workbook-already-open-not-search-value.html

Thanks to MikeTheBike and kirankarnati

Function WorkbookOpen(strWorkBookName As String) As Boolean
    'Returns TRUE if the workbook is open
    Dim oXL As Excel.Application
    Dim oBk As Workbook

    On Error Resume Next
    Set oXL = GetObject(, "Excel.Application")
    If Err.Number <> 0 Then
        'Excel is NOT open, so the workbook cannot be open
        Err.Clear
        WorkbookOpen = False
    Else
        'Excel is open, check if workbook is open
        Set oBk = oXL.Workbooks(strWorkBookName)
        If oBk Is Nothing Then
            WorkbookOpen = False
        Else
            WorkbookOpen = True
            Set oBk = Nothing
        End If
    End If
    Set oXL = Nothing
End Function

Sub testWorkbookOpen()
    Dim strBookName As String
    strBookName = "myWork.xls"
    If WorkbookOpen(strBookName) Then
        msgbox strBookName & " is open", vbOKOnly + vbInformation
    Else
        msgbox strBookName & " is NOT open", vbOKOnly + vbExclamation
    End If
End Sub
Derek Johnson
  • 927
  • 1
  • 11
  • 15
3

This one is a bit easier to understand:

Dim location As String
Dim wbk As Workbook

location = "c:\excel.xls"

Set wbk = Workbooks.Open(location)

'Check to see if file is already open
If wbk.ReadOnly Then
  ActiveWorkbook.Close
    MsgBox "Cannot update the excelsheet, someone currently using file. Please try again later."
    Exit Sub
End If
Bulki
  • 734
  • 1
  • 10
  • 30
1

Checkout this function

'********************************************************************************************************************************************************************************
'Function Name                     : IsWorkBookOpen(ByVal OWB As String)
'Function Description             : Function to check whether specified workbook is open
'Data Parameters                  : OWB:- Specify name or path to the workbook. eg: "Book1.xlsx" or "C:\Users\Kannan.S\Desktop\Book1.xlsm"

'********************************************************************************************************************************************************************************
Function IsWorkBookOpen(ByVal OWB As String) As Boolean
    IsWorkBookOpen = False
    Dim WB As Excel.Workbook
    Dim WBName As String
    Dim WBPath As String
    Err.Clear
    On Error Resume Next
    OWBArray = Split(OWB, Application.PathSeparator)
    Set WB = Application.Workbooks(OWBArray(UBound(OWBArray)))
    WBName = OWBArray(UBound(OWBArray))
    WBPath = WB.Path & Application.PathSeparator & WBName
    If Not WB Is Nothing Then
        If UBound(OWBArray) > 0 Then
            If LCase(WBPath) = LCase(OWB) Then IsWorkBookOpen = True
        Else
            IsWorkBookOpen = True
        End If
    End If
    Err.Clear
End Function
Kannan Suresh
  • 4,573
  • 3
  • 34
  • 59