Close excel if this is the last book?

I have one open book with a SaveClose button. I want the event on this button to close all excel applications if this is the last open book. The fact is that there is a possibility that there may be an unknown open.xlsb open or any other open macro that is not visible, I want to know if any other working excel workbook is open. Is there a check for an invisible book? If this is the last book, close the excel application, if you do not close the active book, this is what I got:

Sub CloseForceSave()

'Save the workbook.
ThisWorkbook.Save

'If this is the only workbook opened in the current session, then...
If Workbooks.Count = 1 Then "or Workbooks.Count = 2" to account for personal.xlsb
'...quit Excel
Application.Quit
'Else...
Else
'...close the active workbook
ThisWorkbook.Close
End If

End Sub
+4
source share
2 answers

, . , . , , , .

Function VisibleWorkbookCount() As Long

    Dim wb As Workbook
    Dim wd As Window
    Dim lReturn As Long

    For Each wb In Application.Workbooks
        For Each wd In wb.Windows
            If wd.Visible Then
                lReturn = lReturn + 1
                Exit For
            End If
        Next wd
    Next wb

    VisibleWorkbookCount = lReturn

End Function
+2
0

Source: https://habr.com/ru/post/1649455/


All Articles