Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 862
Brani Avatar asked Sep 02 '10 14:09

Brani


People also ask

How do you close Excel in VBA without saving?

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.

How do you quit an application in Excel?

Close all workbooks and exit Excel Do one of the following: In the upper-right corner of the Excel window, click Close. . On the File tab, click Exit.


3 Answers

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 
like image 94
variant Avatar answered Sep 22 '22 17:09

variant


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.

like image 31
Leng Keong Avatar answered Sep 23 '22 17:09

Leng Keong


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...

like image 26
kc kalama Avatar answered Sep 19 '22 17:09

kc kalama