+ Reply to Thread
Results 1 to 7 of 7

Check if workbook file is open in another instance of Excel and close if so

Hybrid View

  1. #1
    Valued Forum Contributor
    Join Date
    08-29-2012
    Location
    In lockdown
    MS-Off Ver
    Excel 2010 (2003 to 2016 but 2010 for choice)
    Posts
    1,766

    Check if workbook file is open in another instance of Excel and close if so

    Question as per title. I realise/accept that this could be dangerous in certain situations (e.g. if workbook file currently in use)
    *******************************************************

    HELP WANTED! (Links to Forum threads)
    Trying to create reusable code for Custom Events at Workbook (not Application) level

    *******************************************************

  2. #2
    Valued Forum Contributor saravnepali's Avatar
    Join Date
    01-14-2019
    Location
    Sydney Australia
    MS-Off Ver
    2010
    Posts
    447

    Re: Check if workbook file is open in another instance of Excel and close if so

    Try this code

    Sub Sample()
        Dim Ret
        Dim wbname As String
        wbname = "C:\Users\wbname.xlsx"
        Ret = IsWorkBookOpen(wbname)
        wbnameonly = Right(wbname, Len(wbname) - InStrRev(wbname, "\"))
        MsgBox wbnameonly
        
        If Ret = True Then
        MsgBox "OPen"
            Workbooks(wbnameonly).Close SaveChanges:=False
            
            MsgBox "File " & wbnameonly & " closed by code"
        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
    If you think someone helped you, click on the "* Add Reputation" as a way to say thank you.

    If your problem is solved, go to Thread Tools and select Mark This Thread Solved

  3. #3
    Valued Forum Contributor
    Join Date
    08-29-2012
    Location
    In lockdown
    MS-Off Ver
    Excel 2010 (2003 to 2016 but 2010 for choice)
    Posts
    1,766

    Re: Check if workbook file is open in another instance of Excel and close if so

    TY saravnepali
    I tried the code.
    • It closes the workbook if it is open in the same instance of Excel that the VBA is running in.
    • It doesn't close the workbook if the workbook is open in a different instance of Excel.

  4. #4
    Forum Expert
    Join Date
    01-23-2013
    Location
    USA
    MS-Off Ver
    Microsoft 365 aka Office 365
    Posts
    3,863

    Re: Check if workbook file is open in another instance of Excel and close if so

    Hi,

    See the file associated with post #2 in the following thread (API references coded for 32 bit Excel only): http://www.excelforum.com/excel-prog...instances.html

    The file contains the Macro DisplayDataForAllOpenExcelInstances() below that displays data about each open Excel File in all instances of Excel which should help you get started. There is also a Macro in the file that closes all open Excel Files in All Instances of Excel, except the file that is running the code. Please NOTE that Macro DisplayDataForAllOpenExcelInstances() overwrites the contents of Sheet 'Main' in the 'Active Workbook'. A runtime error will occur if Sheet 'Main' DOES NOT EXIST.
    Option Explicit
    'Reference: cytop (Thank you) http://www.ozgrid.com/forum/showthread.php?t=182853
     
    'The following declarations are for 32 bit Excel only
             
    Private Declare Function FindWindowEx Lib "User32" Alias "FindWindowExA" _
    (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, _
    ByVal lpsz2 As String) As Long
     
    
    Sub ClearA21ToA9999()
      Sheets("Main").Range("A21:A9999").ClearContents
    End Sub
    
    
    Sub DisplayDataForAllOpenExcelInstances()
      'This displays information about all open instances of Excel
      'Reference: cytop (Thank you) http://www.ozgrid.com/forum/showthread.php?t=182853
      
      Dim xlApp As Object
      Dim wb As Object
      Dim ws As Object
      
      Dim iCountInstances As Long
      Dim iCountWorkbooks As Long
      Dim iRow As Long
      Dim hWndXL As Long
      
      'Clear the output area
      Call ClearA21ToA9999
      
      'Set the row number to the row before the first output row
      iRow = 20
      
      'Output a Start message
      iRow = iRow + 1
      Sheets("Main").Cells(iRow, 1) = "DisplayDataForAllOpenExcelInstances() started on " & Now() & "."
           
     'Find the first Excel Window
      hWndXL = FindWindowEx(0&, 0&, "XLMAIN", vbNullString)
         
      'Loop until there are no more Open Instances of Excel
      While hWndXL > 0
             
        'Increment counter
        iCountInstances = iCountInstances + 1
             
        'Print Instance & Handle to Debug window
        iRow = iRow + 1
        iRow = iRow + 1
        iRow = iRow + 1
        Sheets("Main").Cells(iRow, 1) = "Instance #" & iCountInstances & ":  Handle: " & hWndXL
             
        'Get a reference to it
        If GetReferenceToXLApp(hWndXL, xlApp) Then
        
          'Clear the Workbook count
          iCountWorkbooks = 0
                 
          'Iterate through the workbook
          For Each wb In xlApp.Workbooks
          
            'Increment the count of Workbooks in this instance
            iCountWorkbooks = iCountWorkbooks + 1
             
            'Output Workbook name
            iRow = iRow + 1
            iRow = iRow + 1
            Sheets("Main").Cells(iRow, 1) = "Workbook " & iCountWorkbooks & ": " & wb.Name
                     
            'List worksheets in the Workbook
            For Each ws In wb.Worksheets
               iRow = iRow + 1
               Sheets("Main").Cells(iRow, 1) = "Workbook " & iCountWorkbooks & ": " & wb.Name & _
                                               "     Sheet: " & ws.Name
            Next ws
                  
          Next wb
        End If
             
        'Find the next Excel Window
        hWndXL = FindWindowEx(0, hWndXL, "XLMAIN", vbNullString)
             
      Wend
         
    End Sub
    Lewis

  5. #5
    Valued Forum Contributor
    Join Date
    08-29-2012
    Location
    In lockdown
    MS-Off Ver
    Excel 2010 (2003 to 2016 but 2010 for choice)
    Posts
    1,766

    Re: Check if workbook file is open in another instance of Excel and close if so

    Thanks Lewis. I will see if I can get time to test this later this month. Will let you know how it goes.

  6. #6
    Valued Forum Contributor
    Join Date
    08-29-2012
    Location
    In lockdown
    MS-Off Ver
    Excel 2010 (2003 to 2016 but 2010 for choice)
    Posts
    1,766

    Re: Check if workbook file is open in another instance of Excel and close if so

    Thanks for the suggestion Lewis. The 4th goal is now resolved by using GetObject on the open workbook followed by closing the object.

  7. #7
    Forum Expert
    Join Date
    10-06-2017
    Location
    drevni ruchadlo
    MS-Off Ver
    old
    Posts
    2,301

    Re: Check if workbook file is open in another instance of Excel and close if so

    Quote Originally Posted by mc84excel View Post
    Question as per title ...
    1. In total, the topic is not entirely clear, because it is not known whether it is an open file on the local computer, or whether it is an open file from e.g. a company network. Depending on where you open the file, different ways to handle these situations will apply

    2. "Open ...For Input ..."

    This method is not credible (reliable ?), see 'Open' statement description in Microsoft context help:

    "Important - In Binary, Input, and Random modes, you can open a file using a different file number without first closing the file. In Append and Output modes, you must close a file before opening it with a different file number",

    so using 'Input' for 'Open' statement you can open an already open file and declare (state, tell) that it has not been opened before.

    3. A brief "web query" shows interesting solutions that can be customized to this topic.

    A. Solution of Peter Thornton - lists all Excel instances nicely:
    https://social.msdn.microsoft.com/Fo...forum=exceldev

    B. "Check Whether an Excel File Is Open on a Network"
    http://www.java2s.com/Code/VBA-Excel...onaNetwork.htm
    and in many, many places ...
    ... on the forum something would also be found, but I admit that I was not looking here ...

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Check if another workbook is open, close if it is
    By JamesT1 in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 06-11-2019, 09:00 AM
  2. vba excel - close Excel instance from modal form keeps window open
    By terriertrip in forum Excel Programming / VBA / Macros
    Replies: 14
    Last Post: 10-24-2018, 02:37 PM
  3. Replies: 1
    Last Post: 03-23-2018, 03:52 PM
  4. Check if a Word File is Open and If Open Close it with Excel VBA.
    By e4excel in forum Excel Programming / VBA / Macros
    Replies: 5
    Last Post: 12-10-2012, 11:14 AM
  5. Replies: 0
    Last Post: 05-15-2012, 01:09 AM
  6. Close workbook in other instance(?) of excel
    By incjourn in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 06-01-2011, 08:10 PM
  7. Check if workbook is the only Excel File Open
    By duckboy1981 in forum Excel Programming / VBA / Macros
    Replies: 6
    Last Post: 07-17-2009, 12:09 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1