VBA – Close Excel Workbook

Ever needed to ensure a workbook was closed before doing another process, below is a function to accomplish exactly this.

'---------------------------------------------------------------------------------------
' Procedure : XL_CloseWrkBk
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Close a specifc Excel WorkBook
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: Uses Late Binding, so none required
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFileName : Filename (w ext) of the Excel WorkBook to close
'
' Usage:
' ~~~~~~
' Call XL_CloseWrkBk("Accounts.xlsx") 'Close without saving changes
' Call XL_CloseWrkBk("Accounts.xlsx", True) 'Close saving any changes
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2018-11-30              Initial Release (Forum help)
'---------------------------------------------------------------------------------------
Public Sub XL_CloseWrkBk(sFileName As String, Optional bSaveChanges As Boolean = False)
    Dim oExcel                As Object
    Dim oWrkBk                As Object

    On Error Resume Next
    Set oExcel = GetObject(, "Excel.Application")    'Bind to existing instance of Excel
    If Err.Number <> 0 Then    'Excel isn't running
        Err.Clear
        GoTo Error_Handler_Exit
    End If

    On Error GoTo Error_Handler
    '    oExcel.WorkBooks(sFileName).Close
    'Iterate through the open workbooks
    For Each oWrkBk In oExcel.WorkBooks
        If oWrkBk.Name = sFileName Then
            oWrkBk.Close SaveChanges:=bSaveChanges    'Adjust the SaveChanges as suits your needs
        End If
    Next oWrkBk

    'Close Excel if no other WorkBooks are open
    If oExcel.WorkBooks.Count = 0 Then oExcel.Quit

Error_Handler_Exit:
    On Error Resume Next
    If Not oWrkBk Is Nothing Then Set oWrkBk = Nothing
    If Not oExcel Is Nothing Then Set oExcel = Nothing
    Exit Sub

Error_Handler:
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: XL_CloseWrkBk" & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occurred!"
    Resume Error_Handler_Exit
End Sub