+ Reply to Thread
Results 1 to 12 of 12

How to close hidden Excel instances?

Hybrid View

  1. #1
    Forum Contributor
    Join Date
    09-30-2009
    Location
    Barcelona
    MS-Off Ver
    Excel 2010
    Posts
    274

    Question How to close hidden Excel instances?

    Hi,

    I often make macros that retrieve information from files without showing them, by opening them in non-visible instances of excel, but if the macro stops in runtime they may remain open and take more and more resources

    I would like to know if a routine can be programmed to close all excel instances but current one for example (or all of them if it is a must)

    I found this thread but could not manage to get it right

    can anyone give me a hand with that?

    thanks!!
    Last edited by bagullo; 04-29-2011 at 10:02 AM.

  2. #2
    Forum Expert snb's Avatar
    Join Date
    05-09-2010
    Location
    VBA
    MS-Off Ver
    Redhat
    Posts
    5,649

    Re: How to close hidden Excel instances?

    Sub snb()
      With getobject("E:\OF\example.xls")
        c01=.sheets(1).usedrange
        .close false
      end with
    End Sub



  3. #3
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,258

    Re: How to close hidden Excel instances?

    Hello bagullo,

    This macro will close all other separate instances of Excel (hidden or visible) that are running. Only the instance that contains the macro will remain running.
    'Written: April 17, 2011
    'Author:  Leith Ross
    
    'Declare API constants used.
     Private Const GW_CHILD As Long = 5
     Private Const GW_HWNDNEXT = 2
     Private Const MAX_SIZE As Long = 260
     Private Const WM_CLOSE As Long = &H10
    
    'API calls
     Private Declare Function GetWindow _
       Lib "user32.dll" _
         (ByVal hWnd As Long, _
          ByVal wCmd As Long) _
       As Long
    
     Private Declare Function GetDesktopWindow _
       Lib "user32.dll" () As Long
    
     Private Declare Function GetWindowThreadProcessId _
       Lib "user32.dll" _
         (ByVal hWnd As Long, _
          ByRef lpdwProcessId As Long) _
       As Long
         
     Private Declare Function GetClassName _
       Lib "user32.dll" Alias "GetClassNameA" _
         (ByVal hWnd As Long, _
          ByVal lpClassName As String, _
          ByVal nMaxCount As Long) _
       As Long
    
        
     Private Declare Function GetWindowText _
       Lib "user32.dll" Alias "GetWindowTextA" _
         (ByVal hWnd As Long, _
          ByVal lpString As String, _
          ByVal nMaxCount As Long) _
       As Long
     
     Private Declare Function PostMessageA _
       Lib "user32.dll" _
         (ByVal hWnd As Long, _
          ByVal wMsg As Long, _
          ByVal wParam As Long, _
          ByVal lparam As Long) _
       As Long
    
    
    'VBA Macro
    Sub CloseWorkbooks()
     
     'Closes all other workbooks opened in separate instances of Excel.
     
      Dim ClassName As String
      Dim hWnd As Long
      Dim hWndMain As Long
      Dim hWnds() As Variant
      Dim L As Long
      Dim N As Long
      Dim Pid As Long
      Dim RetVal As Long
      Dim WbkName As String
      
         'Save the hWnd of this workbook running the macro
          hWndMain = Application.hWnd
          
         'Start with the Top most window on the Desktop
          hWnd = GetWindow(GetDesktopWindow, GW_CHILD)
    
         'Loop while the hWnd returned by GetWindow is valid.
          While hWnd <> 0
          
            If hWnd <> hWndMain Then
              'Get the Window Class name
               ClassName = String(MAX_SIZE, Chr(0))
               L = GetClassName(hWnd, ClassName, MAX_SIZE)
               ClassName = IIf(L > 0, Left(ClassName, L), "")
               
              'Save the window handles of all Excel instances except this one.
               If ClassName = "XLMAIN" Then
                  ReDim Preserve hWnds(N)
                  hWnds(N) = hWnd
                  N = N + 1
               End If
            End If
               
            'Get the next Window
             hWnd = GetWindow(hWnd, GW_HWNDNEXT)
             
            'Process other events
             DoEvents
          Wend
    
         'Close the workbooks
         'Since window handles are reused, it is safer to use a second loop to close
         'the windows rather than close them in the search loop.
          For I = 0 To UBound(hWnds)
            RetVal = PostMessageA(hWnds(I), WM_CLOSE, 0&, 0&)
              If RetVal = 0 Then
                 WbkName = String(MAX_SIZE, Chr(0))
                 L = GetWindowText(hWnds(I), WkbName, MAX_SIZE)
                 WkbName = IIf(L > 0, Left(WkbName, L), "")
                 MsgBox "Workbook '" & WkbName & "' failed to Close."
              End If
          Next I
          
    End Sub

    Adding the Macro
    1. Copy the macro above pressing the keys CTRL+C
    2. Open your workbook
    3. Press the keys ALT+F11 to open the Visual Basic Editor
    4. Press the keys ALT+I to activate the Insert menu
    5. Press M to insert a Standard Module
    6. Paste the code by pressing the keys CTRL+V
    7. Make any custom changes to the macro if needed at this time.
    8. Save the Macro by pressing the keys CTRL+S
    9. Press the keys ALT+Q to exit the Editor, and return to Excel.

    To Run the Macro...
    To run the macro from Excel, open the workbook, and press ALT+F8 to display the Run Macro Dialog. Double Click the macro's name to Run it.
    Sincerely,
    Leith Ross

    Remember To Do the Following....

    1. Use code tags. Place [CODE] before the first line of code and [/CODE] after the last line of code.
    2. Thank those who have helped you by clicking the Star below the post.
    3. Please mark your post [SOLVED] if it has been answered satisfactorily.


    Old Scottish Proverb...
    Luathaid gu deanamh maille! (Rushing causes delays!)

  4. #4
    Forum Contributor
    Join Date
    09-30-2009
    Location
    Barcelona
    MS-Off Ver
    Excel 2010
    Posts
    274

    Smile Re: How to close hidden Excel instances?

    Thank you Leith!
    that's some awesome piece of code you made
    next time my computer is crowded with loose excel instances I'll give it a shot, it certainly must do the trick!

    Quote Originally Posted by Leith Ross View Post
    Hello bagullo,

    This macro will close all other separate instances of Excel (hidden or visible) that are running. Only the instance that contains the macro will remain running.
    'Written: April 17, 2011
    'Author:  Leith Ross
    
    'Declare API constants used.
     Private Const GW_CHILD As Long = 5
     Private Const GW_HWNDNEXT = 2
     Private Const MAX_SIZE As Long = 260
     Private Const WM_CLOSE As Long = &H10
    
    'API calls
     Private Declare Function GetWindow _
       Lib "user32.dll" _
         (ByVal hWnd As Long, _
          ByVal wCmd As Long) _
       As Long
    
     Private Declare Function GetDesktopWindow _
       Lib "user32.dll" () As Long
    
     Private Declare Function GetWindowThreadProcessId _
       Lib "user32.dll" _
         (ByVal hWnd As Long, _
          ByRef lpdwProcessId As Long) _
       As Long
         
     Private Declare Function GetClassName _
       Lib "user32.dll" Alias "GetClassNameA" _
         (ByVal hWnd As Long, _
          ByVal lpClassName As String, _
          ByVal nMaxCount As Long) _
       As Long
    
        
     Private Declare Function GetWindowText _
       Lib "user32.dll" Alias "GetWindowTextA" _
         (ByVal hWnd As Long, _
          ByVal lpString As String, _
          ByVal nMaxCount As Long) _
       As Long
     
     Private Declare Function PostMessageA _
       Lib "user32.dll" _
         (ByVal hWnd As Long, _
          ByVal wMsg As Long, _
          ByVal wParam As Long, _
          ByVal lparam As Long) _
       As Long
    
    
    'VBA Macro
    Sub CloseWorkbooks()
     
     'Closes all other workbooks opened in separate instances of Excel.
     
      Dim ClassName As String
      Dim hWnd As Long
      Dim hWndMain As Long
      Dim hWnds() As Variant
      Dim L As Long
      Dim N As Long
      Dim Pid As Long
      Dim RetVal As Long
      Dim WbkName As String
      
         'Save the hWnd of this workbook running the macro
          hWndMain = Application.hWnd
          
         'Start with the Top most window on the Desktop
          hWnd = GetWindow(GetDesktopWindow, GW_CHILD)
    
         'Loop while the hWnd returned by GetWindow is valid.
          While hWnd <> 0
          
            If hWnd <> hWndMain Then
              'Get the Window Class name
               ClassName = String(MAX_SIZE, Chr(0))
               L = GetClassName(hWnd, ClassName, MAX_SIZE)
               ClassName = IIf(L > 0, Left(ClassName, L), "")
               
              'Save the window handles of all Excel instances except this one.
               If ClassName = "XLMAIN" Then
                  ReDim Preserve hWnds(N)
                  hWnds(N) = hWnd
                  N = N + 1
               End If
            End If
               
            'Get the next Window
             hWnd = GetWindow(hWnd, GW_HWNDNEXT)
             
            'Process other events
             DoEvents
          Wend
    
         'Close the workbooks
         'Since window handles are reused, it is safer to use a second loop to close
         'the windows rather than close them in the search loop.
          For I = 0 To UBound(hWnds)
            RetVal = PostMessageA(hWnds(I), WM_CLOSE, 0&, 0&)
              If RetVal = 0 Then
                 WbkName = String(MAX_SIZE, Chr(0))
                 L = GetWindowText(hWnds(I), WkbName, MAX_SIZE)
                 WkbName = IIf(L > 0, Left(WkbName, L), "")
                 MsgBox "Workbook '" & WkbName & "' failed to Close."
              End If
          Next I
          
    End Sub

    Adding the Macro
    1. Copy the macro above pressing the keys CTRL+C
    2. Open your workbook
    3. Press the keys ALT+F11 to open the Visual Basic Editor
    4. Press the keys ALT+I to activate the Insert menu
    5. Press M to insert a Standard Module
    6. Paste the code by pressing the keys CTRL+V
    7. Make any custom changes to the macro if needed at this time.
    8. Save the Macro by pressing the keys CTRL+S
    9. Press the keys ALT+Q to exit the Editor, and return to Excel.

    To Run the Macro...
    To run the macro from Excel, open the workbook, and press ALT+F8 to display the Run Macro Dialog. Double Click the macro's name to Run it.

  5. #5
    Forum Contributor
    Join Date
    09-30-2009
    Location
    Barcelona
    MS-Off Ver
    Excel 2010
    Posts
    274

    Re: How to close hidden Excel instances?

    tried it out and works like a charm!

    thnks!

  6. #6
    Forum Contributor
    Join Date
    09-30-2009
    Location
    Barcelona
    MS-Off Ver
    Excel 2010
    Posts
    274

    Red face Re: How to close hidden Excel instances?

    Hi Leith,

    just a small question...

    would it be possible to close those hidden workbooks as "savechanges:=false" so that everything happens behind the scenes?

    sometimes users have told me they feel very confused when excel asks if they want to save chaneges of files they did not open, neither see on their screen.

    I tried to do it myself, but your code is way beyond what I can handle!

    thanks!!

  7. #7
    Forum Expert royUK's Avatar
    Join Date
    11-18-2003
    Location
    Derbyshire,UK
    MS-Off Ver
    Xp; 2007; 2010
    Posts
    26,200

    Re: How to close hidden Excel instances?

    I really can't see why you need to use different instances of Excel, manipulate screenupdating so you can open & close the workbooks withoutthe user seeing in the same instance of Excel.
    Hope that helps.

    RoyUK
    --------
    For Excel Tips & Solutions, free examples and tutorials why not check out my web site

    Free DataBaseForm example

  8. #8
    Forum Contributor
    Join Date
    09-30-2009
    Location
    Barcelona
    MS-Off Ver
    Excel 2010
    Posts
    274

    Re: How to close hidden Excel instances?

    hi roy,
    actually I use that to be able to open other excel workbooks without macros enabled. That makes reading their data much quicker. Plus, I can show user progress, without having them to stare a static screen throughout the process

  9. #9
    Forum Expert snb's Avatar
    Join Date
    05-09-2010
    Location
    VBA
    MS-Off Ver
    Redhat
    Posts
    5,649

    Re: How to close hidden Excel instances?

    Did you ever try opening a workbook like this ? ( in the same Excel instance).

    Sub snb()
     Application.ScreenUpdating = False
     GetObject ("E:\OF\adressen 002.xls")
    End Sub
    And the simplest method I know to close all Excel instances except the one that is triggering this procedure is:

    Sub snb()
     For Each tsk In CreateObject("Word.Application").Tasks
      If InStr(tsk, "Microsoft Excel") Then
       If Split(tsk.Name, "-")(1) <> ThisWorkbook.Name Then tsk.Close
      End If
     Next
    End Sub
    Last edited by snb; 11-17-2011 at 04:35 AM.

  10. #10
    Forum Contributor
    Join Date
    09-30-2009
    Location
    Barcelona
    MS-Off Ver
    Excel 2010
    Posts
    274

    Re: How to close hidden Excel instances?

    Quote Originally Posted by snb View Post
    Did you ever try opening a workbook like this ? ( in the same Excel instance).

    Sub snb()
     Application.ScreenUpdating = False
     GetObject ("E:\OF\adressen 002.xls")
    End Sub
    Nope, never tried, is it better than workbook open? does it open without macros?
    how to you store that in a workbook variable?

    And the simplest method I know to close all Excel instances except the one that is triggering this procedure is:

    Sub snb()
     For Each tsk In CreateObject("Word.Application").Tasks
      If InStr(tsk, "Microsoft Excel") Then
       If Split(tsk.Name, "-")(1) <> ThisWorkbook.Name Then tsk.Close
      End If
     Next
    End Sub
    did not know this way of closing workbooks -- does this work as welll for separate excel applications? I'll keep it in mind.

  11. #11
    Forum Expert snb's Avatar
    Join Date
    05-09-2010
    Location
    VBA
    MS-Off Ver
    Redhat
    Posts
    5,649

    Re: How to close hidden Excel instances?

    Please do not quote (see the forum rules)

    It's much better/faster than workbook open if you want it to be loaded without the user noticing it.
    Why would it be necessary to disable macros ?

    There's no need to store anything in a variable.
    You can always access it using workbooks("filename.xls")

    I posted the second code because it's just doing that.

+ Reply to Thread

Thread Information

Users Browsing this Thread

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

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