VBA close Excel if no other workbooks open

sericom

Well-known Member
Joined
Jan 19, 2006
Messages
923
I have an exit button on a userform with the following code

Private Sub cmdExit_Click()
Application.DisplayAlerts = False
ThisWorkbook.Close
End Sub

I would like it to check to see if any other workbooks are open and if there is then just close the current one only without saving, but if there isn't any other workbooks open I'd like it to close excel.
 

Excel Facts

Shade all formula cells
To shade all formula cells: Home, Find & Select, Formulas to select all formulas. Then apply a light fill color.
Worked it out

Private Sub cmdExit_Click()
Application.DisplayAlerts = False
If Workbooks.Count < 2 Then
Application.Quit
Else
ThisWorkbook.Close
End If
End Sub
 
Upvote 0
In my case, Excel seemed to be counting personal.xlsb as an active workbook so this code wasn't working. I modified to the below and it now works a treat.

If Application.Workbooks.Count = 2 Then
Application.Quit
Else
ThisWorkbook.Close
End If
 
Upvote 0
Worked it out

Private Sub cmdExit_Click()
Application.DisplayAlerts = False
If Workbooks.Count < 2 Then
Application.Quit
Else
ThisWorkbook.Close
End If
End Sub

Genius! Love this place! Just what I needed for my project :)
 
Upvote 0
Worked it out

Private Sub cmdExit_Click()
Application.DisplayAlerts = False
If Workbooks.Count < 2 Then
Application.Quit
Else
ThisWorkbook.Close
End If
End Sub

Maaaaaan thank you sooooo much, you saved my day! I even subscibe to the site just to say it! ;)
 
Upvote 0

Forum statistics

Threads
1,215,220
Messages
6,123,698
Members
449,117
Latest member
Aaagu

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top