Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Closing Excel Workbooks

Status
Not open for further replies.

exRP12Nuke

Technical User
Oct 5, 2011
49
US
Hello,

I am trying to write some code that closes out of Excel when a button is pushed. What I am trying to accomplish is to close the activeworkbook while leaving other workbooks open if there are additional workbooks open at the time that the code is ran; otherwise if the only workbook that is open is the one that I am trying to close, the code will exit out of Excel fully.

Currently what I have is this (simple, I know, but this should be to exit the program):

Code:
Sub Exit_Click()
     
     ThisWorkbook.Close Savechanges:=true

End Sub

Basically what I am trying to do is an If/Then statement, but I am unsure of how to write the code with multiple active workbooks.

Thanks!
 
Try:

Code:
ActiveWorkbook.Close savechanges:=true


- Matt

"If I must boast, I will boast of the things that show my weakness"

- Windows 2003 Server, 98 SE, XP
- VB.NET, VSTS 2010, ASP.NET, EXCEL VBA, ACCESS, SQL 2008
 
If you want to close Excel then try putting application.quit after thisworkbok.save savechanges: = True

Activworkbook.close will close whatever workbook is currently active regardless of which on is running the code.

Thisworkbook.close will close the workbok that has that specific line of code in it.
 
tqeonline,

Still the same issue. Perhaps I did not explain it clearly enough. Say that there are two Workbooks open (Book1 and Book2), and I am trying to close Book1 without closing Book2, the ActiveWorkbook.Close command works great. However, if only Book1 is open, then the workbook closes but Excel stays open.
 
psuedo code
Code:
For x = 1 to activeworkbooks.count
Workbooks(x).Activate
ActiveWorkbook.Close savechanges:=true 
next x
application.quit

- Matt

"If I must boast, I will boast of the things that show my weakness"

- Windows 2003 Server, 98 SE, XP
- VB.NET, VSTS 2010, ASP.NET, EXCEL VBA, ACCESS, SQL 2008
 


hi,

check out workbooks.count.

Skip,
[sub]
[glasses]Just traded in my old subtlety...
for a NUANCE![tongue][/sub]
 
Thank you everyone, this works perfectly!

Code:
Sub Exit_Click()

     If Workbooks.Count > 1 Then
          ThisWorkbook.Close savechanges:=True
     Else
          Application.Quit
     End If

End Sub

Thanks again for all of the help!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top