Application quit vba excel не закрывает приложение
Cause
Resolution
To make sure that the Office application exits, determine whether your automation code meets the following criteria:
Declare each object as a new variable. For example, change the following line of code:
Change this to the following:
To release the reference to the variable, set the variable equal to Nothing or Null.
Use the Quit method of the Office application object to tell the server to shut down.
Status
This behavior is by design.
More Information
Steps to reproduce the behavior
On the File menu, click New, and then click Project. Under Visual Basic Projects, select Windows Application, and then click OK.
Note Form1 is created by default.
Add a reference to the Microsoft Excel Object Library. To do this, follow these steps:
On the Project menu, click Add Reference.
On the COM tab, locate the Object Library for Excel, and then click Select.
For Microsoft Excel 2002: Microsoft Excel 10.0 Object Library
Note If you have not already done this, we recommend that you download and install the Microsoft Office XP Primary Interop Assemblies (PIAs).
For more information about Office XP PIAs, go to the following Microsoft Knowledge Base article:
328912 Microsoft Office XP primary interop assemblies (PIAs) are available for download
For Microsoft Office Excel 2003: Microsoft Excel 11.0 Object Library
Click OK in the Add References dialog box to accept your selections.
On the View menu, click Toolbox, and then drag a Button control onto Form1.
Note The code window for the form appears.
Add the following code to the top of Form1.vb:
Replace the following code in the code window:
Substitute the following code:
Press F5 to run the application.
Open Windows Task Manager. In Visual Studio, display the Output window to see the debug messages. Click the command button. Notice that an instance of Excel.exe appears in the Processes list.
The instance of Excel still runs in the task list even after the application has finished sleeping. Close the dialog box and notice that Excel no longer appears in the Processes list.
When you do the steps in the "Resolution" section, the Office application exits after it releases the last variable. Replace the function in Step 5 by using the following code:
Troubleshooting
Note If you follow the steps that are described in the "Steps to Reproduce the Behavior" section, and the server still does not shut down, you can use the GC.Collect() method and the GC.WaitForPendingFinalizers() method after you release the last object. Because the runtime performs garbage collection on the RCW, the GC.Collect() method forces the garbage collector to run and might release any references that the RCW still has. The GC.Collect() method tries to reclaim the maximum memory that is available. Notice that this does not guarantee that all memory will be reclaimed.
I have following code under a button. When clicked it just closes the current Excel sheet but not the entire Excel application.
Note: I don't have any other sheets open.
The following window still appears.
12 Answers 12
I had this issue and I resolved it by putting in the Workbook_BeforeClose() :
This is more than likely the answer, because it sounds like you have a dialog that isn't being dealt with and is therefore preventing the application from quitting. This will prevent a save dialog from appearing during the workbook closing.
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
my excel will open in read only as it is a public file. So i dont want any prompt ! I have ur suggesstion but same result. Probably this is not my answer
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 .
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"
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
I did not try it, but maybe this will help:
According to Norie you might not have anymore workbooks open, therefore Application.Quit will never be executed.
AlphaFrog therefore suggests this:
I had the same issue using the following code closed excel cleanly:
This will allow excel to cleanly close without keeping a "ghost" window open.
This worked for me: (Office 365)
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.
У меня есть следующий код под кнопкой. При нажатии он просто закрывает текущий лист Excel, но не все приложение Excel.
Примечание: у меня нет других открытых листов.
Следующее окно все еще появляется.
У меня была эта проблема, и я решил ее, добавив Workbook_BeforeClose() :
Это более чем вероятный ответ, потому что похоже, что у вас есть диалог, который не обрабатывается и, следовательно, предотвращает выход приложения. Это предотвратит появление диалогового окна сохранения во время закрытия книги.
убрать Application.DisplayAlerts = True из распорядка.
из справки по 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.
Это позволит избежать любых (возможно, скрытых) подсказок, не позволяющих полностью закрыть Excel.
мой Excel будет открыт только для чтения, поскольку это общедоступный файл. Так что я не хочу никаких подсказок! У меня есть ваше предложение, но результат тот же. Наверное это не мой ответ
У меня возникла та же проблема, и я смог решить ее с помощью кода, который проверяет, открыты ли несколько книг или нет .
Когда в подпрограмме встречается Application.Quit, он остается только в памяти и продолжает выполнять строки под ним и фактически завершает работу до тех пор, пока не встретит «Exit Sub». При обнаружении обычного «End Sub» на первичном уровне он также закроет Excel. Но скажем, если книга каким-то образом закрывается до того, как дойдет до строки «Выход из подпрограммы», «Конец» или «Конец подпрограммы», тогда Excel не закроется.
Решение состоит в том, чтобы создать общедоступную переменную ToQuitNow с начальным значением False и изменить ее на True в том месте, где вы хотите завершить работу Excel. и проверьте сразу после этого, чтобы убедиться, что это правда, затем вернитесь на предыдущий подуровень с помощью «Exit Sub» или «End», чтобы сразу выйти, и сделайте то же самое на каждом подпрограмме, где ожидается возврат из более глубокой подпрограммы. Когда он возвращается на основной уровень, последний «Exit Sub» фактически завершает работу Excel. Если вы не хотите, чтобы Excel запрашивал сохранение внесенных изменений, добавьте строку «ThisWorkbook.Saved = True» сразу после Application.Quit или перед последним «Exit Sub» на основном уровне, и Excel выйдет без сохранения.
У меня есть следующий код под кнопкой. При нажатии он просто закрывает текущий лист Excel, но не все приложение Excel.
Примечание. У меня нет других открытых листов.
По-прежнему появляется следующее окно.
У меня была эта проблема, и я решил ее, вставив Workbook_BeforeClose() :
Это более чем вероятный ответ, потому что похоже, что у вас есть диалог, который не обрабатывается и, следовательно, предотвращает выход приложения. Это предотвратит появление диалогового окна сохранения во время закрытия книги.
удалить Application.DisplayAlerts = True из рутины.
из справки для 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.
Это позволит избежать любых (возможно, скрытых) подсказок от полного закрытия excel.
мой Excel откроется только для чтения, так как это общедоступный файл. Так что я не хочу никакой подсказки! У меня есть ваше предложение, но тот же результат. Наверное это не мой ответ
Я столкнулся с той же проблемой и смог решить проблему с помощью кода, который проверяет, открыты ли несколько книг или нет.
Когда Application.Quit встречается в подпрограмме, он остается только в памяти и продолжает выполнять строки под ним и фактически завершает работу до тех пор, пока не встретит «Exit Sub». Когда встречается обычный «End Sub» на основном уровне, он также закрывает Excel. Но скажем, если рабочая книга каким-то образом закрывается до достижения строки «Exit Sub», «End» или «End Sub», Excel не закроется.
Решение состоит в том, чтобы создать общедоступную переменную с именем ToQuitNow с начальным значением False и изменить ее на True там, где вы хотите закрыть Excel. и проверьте сразу после этого, чтобы убедиться, что это правда, затем вернитесь на предыдущий подуровень с помощью «Exit Sub» или «End», чтобы выйти сразу, и сделайте то же самое на каждом уровне подпрограммы, где ожидается возврат из более глубокой подпрограммы. Когда он вернется на основной уровень, последний «Exit Sub» фактически закроет Excel. Если вы не хотите, чтобы Excel запрашивал сохранение внесенных изменений, добавьте строку «ThisWorkbook.Saved = True» сразу после Application.Quit или перед последним «Exit Sub» на начальном уровне, и Excel завершит работу без сохранения.
nilem, в итоге у меня всё давно работает, наверное, неправильно и бредово. Не тормозит, не зависает, не приводит к неоднозначностям.
У меня остались вопросы по работе кода, о них я и вопрошаю.
Повторю эти вопросы.
1. Application.Quit произойдёт только после End Sub, а помещать его можно в любое место кода?
2. Почему MsgBox срабатывает дважды в кодах
[vba]
Private Sub Workbook_BeforeClose(Cancel As Boolean)
…
If Cells(1, 1) = "" And Workbooks.Count = 1 Then MsgBox "1": ThisWorkbook.Close (False): MsgBox "2": Application.Quit
MsgBox "3"
…
Private Sub Workbook_BeforeClose(Cancel As Boolean, k As Byte)
…
With Range("E2:E" & lr + 8)
…
.ClearContents
End With
ThisWorkbook.Save
If Workbooks.Count = 1 Then MsgBox "Quit " & k: k = k + 1: Application.Quit
End Sub
[/vba]
при наличии .ClearContents
3. Если из Private Sub сделать Call Workbook_BeforeClose, то закрытия файла не происходит. Верно я понимаю, что Workbook_BeforeClose с Call работает как обычная Sub – книгу не закрывает и передаёт очередь по окончании своей работы вызвавшей её Private Sub?
nilem, в итоге у меня всё давно работает, наверное, неправильно и бредово. Не тормозит, не зависает, не приводит к неоднозначностям.
У меня остались вопросы по работе кода, о них я и вопрошаю.
Повторю эти вопросы.
1. Application.Quit произойдёт только после End Sub, а помещать его можно в любое место кода?
2. Почему MsgBox срабатывает дважды в кодах
[vba]
Private Sub Workbook_BeforeClose(Cancel As Boolean)
…
If Cells(1, 1) = "" And Workbooks.Count = 1 Then MsgBox "1": ThisWorkbook.Close (False): MsgBox "2": Application.Quit
MsgBox "3"
…
Private Sub Workbook_BeforeClose(Cancel As Boolean, k As Byte)
…
With Range("E2:E" & lr + 8)
…
.ClearContents
End With
ThisWorkbook.Save
If Workbooks.Count = 1 Then MsgBox "Quit " & k: k = k + 1: Application.Quit
End Sub
[/vba]
при наличии .ClearContents
3. Если из Private Sub сделать Call Workbook_BeforeClose, то закрытия файла не происходит. Верно я понимаю, что Workbook_BeforeClose с Call работает как обычная Sub – книгу не закрывает и передаёт очередь по окончании своей работы вызвавшей её Private Sub?
Private Sub Workbook_BeforeClose(Cancel As Boolean)
…
If Cells(1, 1) = "" And Workbooks.Count = 1 Then MsgBox "1": ThisWorkbook.Close (False): MsgBox "2": Application.Quit
MsgBox "3"
…
Private Sub Workbook_BeforeClose(Cancel As Boolean, k As Byte)
…
With Range("E2:E" & lr + 8)
…
.ClearContents
End With
ThisWorkbook.Save
If Workbooks.Count = 1 Then MsgBox "Quit " & k: k = k + 1: Application.Quit
End Sub
[/vba]
при наличии .ClearContents
3. Если из Private Sub сделать Call Workbook_BeforeClose, то закрытия файла не происходит. Верно я понимаю, что Workbook_BeforeClose с Call работает как обычная Sub – книгу не закрывает и передаёт очередь по окончании своей работы вызвавшей её Private Sub?
Читайте также: