VBA to close any open excel file and excel application [duplicate] - excel

I have following code under a button. When clicked it just closes the current Excel sheet but not the entire Excel application.
Application.DisplayAlerts = False
ThisWorkbook.Save
Application.DisplayAlerts = True
Application.Quit
Note: I don't have any other sheets open.
The following window still appears.

I had this issue and I resolved it by putting in the Workbook_BeforeClose():
ThisWorkbook.saved = true

I experienced the same issue and was able to resolve the issue with code that looks to see if multiple workbooks are open or not ...
Application.EnableEvents = False
Application.DisplayAlerts = False
If Application.Workbooks.Count = 1 Then 'Close Excel application
ThisWorkbook.Save
Application.Quit
Else 'Close the active workbook
With ActiveWorkbook
.Close Savechanges:=True
End With
End If

When Application.Quit is encountered in a subroutine,
it will only stay in memory and continue to run lines under it
and will actually quit until it encounters a "Exit Sub".
When the normal "End Sub" at the primary level is encountered,
it will then also close Excel. But say if the workbook is somehow
closed before reaching the "Exit Sub", "End" or "End Sub" line, then
Excel will not close.
Solution is to create a Public variable called ToQuitNow
with initial False value
and change it to True where you want Excel to quit.
and test right after to see if it is true, then return to previous Sub level
by "Exit Sub" or "End" to quit right away,
and do the same at every subrountine level where
it is expected to return from the deeper subroutine.
When it gets back to the primary level,
then a final "Exit Sub" will actually terminates Excel.
If you do not want Excel to ask for saving changes made,
add line "ThisWorkbook.Saved = True" right after Application.Quit,
or before the final "Exit Sub" at the Primary level
and Excel will quit without saving.
Try the following test below, just run "Test"
Public ToQuitNow As Boolean
Sub Test()
ToQuitNow = False ' initialize with False value
Call SecondSub
MsgBox ("Primary level here. Back from SecondSub")
If ToQuitNow = True Then
Exit Sub 'will actually quit Excel now if True
End If
MsgBox ("This line will not run if ToQuitNow is True")
End Sub
Sub SecondSub()
MsgBox ("SecondSub here")
Call ThirdSub
MsgBox ("SecondSub here. Back from ThirdSub")
If ToQuitNow = True Then
Exit Sub ' will return to Main level if True
End If
MsgBox ("This line from SecondSub will not run if ToQuitNow is True")
End Sub
Sub ThirdSub()
MsgBox ("ThirdSub here")
Call FourthSub
MsgBox ("ThirdSub here. Back from FourthSub")
If ToQuitNow = True Then
Exit Sub ' will return to SecondSub if True
End If
MsgBox ("This line from ThirdSub will not run if ToQuitNow is True")
End Sub
Sub FourthSub()
MsgBox ("FourthSub here")
Application.Quit
ThisWorkbook.Saved = True ' Excel will think changes already saved _
and will quit without saving
ToQuitNow = True ' activate Quit
If ToQuitNow = True Then
MsgBox ("Quit command executed in FourthSub")
Exit Sub ' will return to ThirdSub if True
'Can also put in End in above line to quit right away
End If
MsgBox ("This line from FourthSub will not run if ToQuitNow is True.")
End Sub

remove the Application.DisplayAlerts = True from the routine.
from the help for Application.Quit Method:
If unsaved workbooks are open when you use this method, Microsoft Excel displays a dialog box asking whether you want to save the changes. You can prevent this by saving all workbooks before using the Quit method or by setting the DisplayAlerts property to False. When this property is False, Microsoft Excel doesn’t display the dialog box when you quit with unsaved workbooks; it quits without saving them.
This will avoid any (possibly hidden) prompts from stopping excel from closing completely

I did not try it, but maybe this will help:
https://www.mrexcel.com/forum/excel-questions/606195-vba-application-quit-not-working-me-completly-why.html
According to Norie you might not have anymore workbooks open, therefore Application.Quit will never be executed.
AlphaFrog therefore suggests this:
Application.DisplayAlerts = False
If Application.Workbooks.Count = 1 Then
Application.Quit
Else
ActiveWorkbook.Close
End If

The window does not close because you are using personal.xlsb. Cut Personal.xlsb and paste in another location.
Instead of Personal.xlsb create and work on modules. It's a better option.

"ThisWorkbook.Saved = True" after "Application.Quit" works on Excel 2016
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.Quit
ThisWorkbook.Saved = True
End Sub

I had the same issue using the following code closed excel cleanly:
Application.DisplayAlerts = False
ThisWorkbook.Save
Application.Quit
This will allow excel to cleanly close without keeping a "ghost" window open.

This worked for me: (Office 365)
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.DisplayAlerts = False
Application.EnableEvents = False
ThisWorkbook.Save
Application.Quit
ThisWorkbook.Saved = True
End Sub

This is a strange one, hopefully someone will find this answer useful. I ran into something very similar using Excel 2010 (14.0). I stumbled to my answer through experimentation. This is bad answer for general purpose.
For whatever reason Application.Quit fails silently if the option AccessVBOM is not enabled. It is not enabled out of the box and can be set/unset by your network admin by windows policy.
You can find this option in the GUI by traversing "Excel Options" -> "Trust Center" -> "Trust Center Settings" -> "Macro Settings" -> "Trust access to the VBA project object model". Or programmatically.
.
Since we all love code, in this example we are running Excel from C# interop and calling the quit function.
using Excel = Microsoft.Office.Interop.Excel;
using Marshal = System.Runtime.InteropServices.Marshal;
Excel.Application app = new Excel.Application();
app.Visible = false;
app.DisplayAlerts = false;
// this will hang if AccessVBOM is not enabled
app.Quit();
Marshal.ReleaseComObject(app);

Have passed MacroName from bat file and tried the below code its working. But one thing I observed is if we are closing the workbook(ActiveWorkbook.Close) before Application.Quit then it is not working.
Private Sub Auto_Open()
Dim strMacroName As String
strMacroName =
VBA.CreateObject("WScript.Shell").Environment("process").Item("MacroName")
If strMacroName <> "" Then Run strMacroName
Application.DisplayAlerts = False
ThisWorkbook.Save
Application.DisplayAlerts = True
If strMacroName <> "" Then Application.Quit
End Sub
Sub Button1_Click()
MsgBox ("done")
End Sub

Make sure that your sheets do not have any external link references, especially broken links.
I struggled with this problem for more than a week, rewriting and commenting out lots of code to try to isolate the problem. I finally did a review of all table and external sheet references in my workbook this morning. I removed all unnecessary links and broken references and the workbook now closes without hanging in memory.

Related

Excel VBA application.visible immediately set back to True

I have set up a new, empty, modeless userform, to fix my problem with the least amount of code involved.
For when the workbook is opened, the following code is executed to hide Excel and show the userform. It's the only code for the workbook.
Private Sub Workbook_Open()
UserForm1.Show
If Application.Windows.Count <> 1 Then
Application.Windows("test.xlsm").Visible = False
Else
Application.Visible = False
End If
End Sub
I have an empty userform with one single button. The only code for this userform is:
Private Sub CommandButton1_Click()
Application.Windows("test.xlsm").Visible = True
Application.Visible = True
Unload Me
End Sub
The last thing is a button on the first worksheet, to start the same process as when the workbook is opened. Its code:
Sub Button1_Click()
UserForm1.Show
If Application.Windows.Count <> 1 Then
Application.Windows("test.xlsm").Visible = False
Else
Application.Visible = False
End If
End Sub
Now my problem:
When I open the workbook, the userform shows up, but excel and the active window stay visible as well. However, if I click the button on the worksheet, Excel, or the window, are hidden as they should. Also, Excel, not the userform, has focus after loading everything.
The first time I ran this, it worked fine. I suspect changing the ShowModal setting in the editor screwed it up somehow, but that's just me guessing. Anyway, it doesn't work anymore as intended, no matter the modal setting now.
If I just run
Application.Visible = False
instead of the "if"-clause, Excel still stays visible and of course so does the active window.
This is driving me nuts.
What am I missing?
Edit: Link to my test file: Test File on my Dropbox
Might have to start it twice, because when the macros are blocked at startup and only activated after excel has completely loaded, the code works as intended.
Edit: I was able to test this on an excel 2010 pc and there the problem doesn't exist. So it might have something to do with the way newer Office Apps handle stuff.
I found myself having the exact same problem - modeless form opened with Workbook_Open() event that's also supposed to hide excel app (working on Excel 2016, 32bit).
The reason why it's working with UserForm property ShowModal set to True is because: the execution is suspended - it's waiting for user to interact with the UserForm that was shown.
If we change ShowModal to False (or call UserForm.Show vbModeless) then the execution is never suspended and once we reach End Sub of our Workbook_Open(), Excel appears to set Application.Visible = True on its own.
Only solution I've found thus far is this one - basically you suspend the execution by adding an infinite loop so Excel only gets to end of this event once you get rid of (Unload/Hide) the form that was shown previously.
My version looks like this:
Private Sub Workbook_Open()
Dim App As Object
Set App = startMenu
App.Show vbModeless
While App.Visible
DoEvents
Wend
End Sub
Then just to make sure that Excel is closed once that modeless UserForm is closed I've added this:
Private Sub UserForm_Terminate()
CloseApp
End Sub
Public Sub CloseApp()
ThisWorkbook.Saved = True
If Not OtherWorkbooksOpen Then
Application.Quit
Else
ThisWorkbook.Close
End If
End Sub
Public Function OtherWorkbooksOpen()
If Application.Workbooks.Count > 1 Then
OtherWorkbooksOpen = True
Else
OtherWorkbooksOpen = False
End If
End Function
EDIT:
Solution without infinite loop - schedule hiding of Excel:
Private Sub Workbook_Open()
Dim App As Object
Set App = startMenu
App.Show
If Not OtherWorkbooksOpen Then
Application.OnTime Now + TimeValue("00:00:01"), "HideExcel"
End If
End Sub
I think the userform1.show needs to be called after the execution of if statement.
Private Sub Workbook_Open()
If Application.Windows.Count <> 1 Then
Application.Windows("test.xlsm").Visible = False
Else
Application.Visible = False
End If
UserForm1.Show
End Sub
Not an answer, but I can't post this as a comment. This works for me - the user form appears, the application is hidden. I used "<>2" as I have a personal workbook. Can you confirm what happens for you?
Private Sub Workbook_Open()
If Application.Windows.Count <> 2 Then
Application.Windows("test.xlsm").Visible = False
Else
Application.Visible = False
End If
UserForm1.Show False
End Sub
I had the same issue, but I notice the form loads before the excel file. So I put a redundancy calling the application.visible = false, in the form.
Basically after clicking anything in the form, it will call the application.visible = false and the excel window will hide.

Proper VBA code to close workbook without saving

Whenever the code is executed while multiple workbooks are open, office stops working with a message
Microsoft Office Excel has stopped working
Windows can try to recover your information and restart the program.
What's wrong with the code? I'm using MS Office 2007 on Windows7
Private Sub Workbook_BeforeClose(Cancel As Boolean)
close_without_saving
End Sub
Sub close_without_saving()
Application.DisplayAlerts = False
ThisWorkbook.Saved = True
If Application.Workbooks.Count < 2 Then
Application.Quit
Else
ThisWorkbook.Close
End If
End Sub
If you want to close the workbook without incorporating changes. Then you can use code like this in workbook module ~
Sub Auto_Close()
ThisWorkbook.Saved = True
End Sub
You can also use this for closing workbook without saving changes.
Sub CloseBook2()
ActiveWorkbook.Close savechanges:=False
End Sub
This routine can be attached to Close X Button. Workbook never closes partially, it will always close with all sheets contained in this workbook. DisplayAlerts = False and subsequently True can be incorporated in the routine. That should not create a problem like
Sub CloseBook()
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub

Excel application won't quit after checking in to sharepoint

I am having trouble quitting the excel application after checking in to sharepoint. I have the following code in the thisworkbook module:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.EnableEvents = False
Application.ScreenUpdating = False
ThisWorkbook.Save
If Workbooks.Count < 2 Then
Application.Quit
Else
ThisWorkbook.Close
End If
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.EnableEvents = True
If ThisWorkbook.CanCheckIn Then
ThisWorkbook.CheckIn
Else
MsgBox ("This workbook cannot be checked in.")
End If
End Sub
The file is successful in checking in to sharepoint. The workbook gets closed but the excel application is still running. How do I terminate the application?
Thanks.
Application.Quit
Should do the trick. Add that when you want to close Excel.
I've been having a similar problem and I found a quick discussion on what could be causing the Excel instance to not quit.
Excel won't quit
And here is an absolutely awful way to get around having to properly code.
How Can I Kill Task Manager Processes Through VBA code

Application.Quit command not closing the entire Excel Application

I have following code under a button. When clicked it just closes the current Excel sheet but not the entire Excel application.
Application.DisplayAlerts = False
ThisWorkbook.Save
Application.DisplayAlerts = True
Application.Quit
Note: I don't have any other sheets open.
The following window still appears.
I had this issue and I resolved it by putting in the Workbook_BeforeClose():
ThisWorkbook.saved = true
I experienced the same issue and was able to resolve the issue with code that looks to see if multiple workbooks are open or not ...
Application.EnableEvents = False
Application.DisplayAlerts = False
If Application.Workbooks.Count = 1 Then 'Close Excel application
ThisWorkbook.Save
Application.Quit
Else 'Close the active workbook
With ActiveWorkbook
.Close Savechanges:=True
End With
End If
When Application.Quit is encountered in a subroutine,
it will only stay in memory and continue to run lines under it
and will actually quit until it encounters a "Exit Sub".
When the normal "End Sub" at the primary level is encountered,
it will then also close Excel. But say if the workbook is somehow
closed before reaching the "Exit Sub", "End" or "End Sub" line, then
Excel will not close.
Solution is to create a Public variable called ToQuitNow
with initial False value
and change it to True where you want Excel to quit.
and test right after to see if it is true, then return to previous Sub level
by "Exit Sub" or "End" to quit right away,
and do the same at every subrountine level where
it is expected to return from the deeper subroutine.
When it gets back to the primary level,
then a final "Exit Sub" will actually terminates Excel.
If you do not want Excel to ask for saving changes made,
add line "ThisWorkbook.Saved = True" right after Application.Quit,
or before the final "Exit Sub" at the Primary level
and Excel will quit without saving.
Try the following test below, just run "Test"
Public ToQuitNow As Boolean
Sub Test()
ToQuitNow = False ' initialize with False value
Call SecondSub
MsgBox ("Primary level here. Back from SecondSub")
If ToQuitNow = True Then
Exit Sub 'will actually quit Excel now if True
End If
MsgBox ("This line will not run if ToQuitNow is True")
End Sub
Sub SecondSub()
MsgBox ("SecondSub here")
Call ThirdSub
MsgBox ("SecondSub here. Back from ThirdSub")
If ToQuitNow = True Then
Exit Sub ' will return to Main level if True
End If
MsgBox ("This line from SecondSub will not run if ToQuitNow is True")
End Sub
Sub ThirdSub()
MsgBox ("ThirdSub here")
Call FourthSub
MsgBox ("ThirdSub here. Back from FourthSub")
If ToQuitNow = True Then
Exit Sub ' will return to SecondSub if True
End If
MsgBox ("This line from ThirdSub will not run if ToQuitNow is True")
End Sub
Sub FourthSub()
MsgBox ("FourthSub here")
Application.Quit
ThisWorkbook.Saved = True ' Excel will think changes already saved _
and will quit without saving
ToQuitNow = True ' activate Quit
If ToQuitNow = True Then
MsgBox ("Quit command executed in FourthSub")
Exit Sub ' will return to ThirdSub if True
'Can also put in End in above line to quit right away
End If
MsgBox ("This line from FourthSub will not run if ToQuitNow is True.")
End Sub
remove the Application.DisplayAlerts = True from the routine.
from the help for Application.Quit Method:
If unsaved workbooks are open when you use this method, Microsoft Excel displays a dialog box asking whether you want to save the changes. You can prevent this by saving all workbooks before using the Quit method or by setting the DisplayAlerts property to False. When this property is False, Microsoft Excel doesn’t display the dialog box when you quit with unsaved workbooks; it quits without saving them.
This will avoid any (possibly hidden) prompts from stopping excel from closing completely
I did not try it, but maybe this will help:
https://www.mrexcel.com/forum/excel-questions/606195-vba-application-quit-not-working-me-completly-why.html
According to Norie you might not have anymore workbooks open, therefore Application.Quit will never be executed.
AlphaFrog therefore suggests this:
Application.DisplayAlerts = False
If Application.Workbooks.Count = 1 Then
Application.Quit
Else
ActiveWorkbook.Close
End If
The window does not close because you are using personal.xlsb. Cut Personal.xlsb and paste in another location.
Instead of Personal.xlsb create and work on modules. It's a better option.
"ThisWorkbook.Saved = True" after "Application.Quit" works on Excel 2016
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.Quit
ThisWorkbook.Saved = True
End Sub
I had the same issue using the following code closed excel cleanly:
Application.DisplayAlerts = False
ThisWorkbook.Save
Application.Quit
This will allow excel to cleanly close without keeping a "ghost" window open.
This worked for me: (Office 365)
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.DisplayAlerts = False
Application.EnableEvents = False
ThisWorkbook.Save
Application.Quit
ThisWorkbook.Saved = True
End Sub
This is a strange one, hopefully someone will find this answer useful. I ran into something very similar using Excel 2010 (14.0). I stumbled to my answer through experimentation. This is bad answer for general purpose.
For whatever reason Application.Quit fails silently if the option AccessVBOM is not enabled. It is not enabled out of the box and can be set/unset by your network admin by windows policy.
You can find this option in the GUI by traversing "Excel Options" -> "Trust Center" -> "Trust Center Settings" -> "Macro Settings" -> "Trust access to the VBA project object model". Or programmatically.
.
Since we all love code, in this example we are running Excel from C# interop and calling the quit function.
using Excel = Microsoft.Office.Interop.Excel;
using Marshal = System.Runtime.InteropServices.Marshal;
Excel.Application app = new Excel.Application();
app.Visible = false;
app.DisplayAlerts = false;
// this will hang if AccessVBOM is not enabled
app.Quit();
Marshal.ReleaseComObject(app);
Have passed MacroName from bat file and tried the below code its working. But one thing I observed is if we are closing the workbook(ActiveWorkbook.Close) before Application.Quit then it is not working.
Private Sub Auto_Open()
Dim strMacroName As String
strMacroName =
VBA.CreateObject("WScript.Shell").Environment("process").Item("MacroName")
If strMacroName <> "" Then Run strMacroName
Application.DisplayAlerts = False
ThisWorkbook.Save
Application.DisplayAlerts = True
If strMacroName <> "" Then Application.Quit
End Sub
Sub Button1_Click()
MsgBox ("done")
End Sub
Make sure that your sheets do not have any external link references, especially broken links.
I struggled with this problem for more than a week, rewriting and commenting out lots of code to try to isolate the problem. I finally did a review of all table and external sheet references in my workbook this morning. I removed all unnecessary links and broken references and the workbook now closes without hanging in memory.

Closing Excel Application using VBA

I have used the following without success. The active workbook closes, indeed, but the excel window remains open.
Application.ActiveWindow.Close SaveChanges:=False
ActiveWorkbook.Close SaveChanges:=False
Which is the command that terminates the application?
EDIT
To say a little more: In the workbook Open event I run a macro. I want to terminate the application when that macro finishes. I also tried this without success.
Private Sub Workbook_Open()
Macro_MyJob
Application.Quit
End Sub
Where should I put this Application.Quit command?
I think your problem is that it's closing the document that calls the macro before sending the command to quit the application.
Your solution in that case is to not send a command to close the workbook. Instead, you could set the "Saved" state of the workbook to true, which would circumvent any messages about closing an unsaved book. Note: this does not save the workbook; it just makes it look like it's saved.
ThisWorkbook.Saved = True
and then, right after
Application.Quit
To avoid the Save prompt message, you have to insert those lines
Application.DisplayAlerts = False
ThisWorkbook.Save
Application.DisplayAlerts = True
After saving your work, you need to use this line to quit the Excel application
Application.Quit
Don't just simply put those line in Private Sub Workbook_Open() unless you got do a correct condition checking, else you may spoil your excel file.
For safety purpose, please create a module to run it. The following are the codes that i put:
Sub testSave()
Application.DisplayAlerts = False
ThisWorkbook.Save
Application.DisplayAlerts = True
Application.Quit
End Sub
Hope it help you solve the problem.
Sub TestSave()
Application.Quit
ThisWorkBook.Close SaveChanges = False
End Sub
This seems to work for me, Even though looks like am quitting app before saving, but it saves...
Application.Quit
Should do the trick.
I tried a certain sequence that seems to work as you can see below:
ThisWorkbook.Saved = True
Application.Quit
Application.ActiveWindow.Close SaveChanges:=False
ActiveWorkbook.Close SaveChanges:=False
You can try out
ThisWorkbook.Save
ThisWorkbook.Saved = True
Application.Quit
In my case, I needed to close just one excel window and not the entire application, so, I needed to tell which exact window to close, without saving it.
The following lines work just fine:
Sub test_t()
Windows("yourfilename.xlsx").Activate
ActiveWorkbook.Close SaveChanges:=False
End Sub
Sub button2_click()
'
' Button2_Click Macro
'
' Keyboard Shortcut: Ctrl+Shift+Q
'
ActiveSheet.Shapes("Button 2").Select
Selection.Characters.Text = "Logout"
ActiveSheet.Shapes("Button 2").Select
Selection.OnAction = "Button2_Click"
ActiveWorkbook.Saved = True
ActiveWorkbook.Save
Application.Quit
End Sub

Resources