Access – VBA – Close All Open Queries

Continuing down the same path as my previous post:

I thought I’d share a simple function to close any and all open queries.

The concept is the same in that we loop through all the queries (CurrentData.AllQueries), check to see if each one is loaded (IsLoaded), and if so, close them (DoCmd.Close).

The Code

'---------------------------------------------------------------------------------------
' Procedure : CloseAllOpenQueries
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Close all the currently open Queries in the database
' 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: None required
'
' Usage:
' ~~~~~~
' ? CloseAllOpenQueries
'   Returns -> True     => Closed all Queries successfully
'              False    => A problem occurred
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2015-02-17              Initial Release
' 2         2023-02-09              Update variable naming, Error handler, copyright
'---------------------------------------------------------------------------------------
Function CloseAllOpenQueries() As Boolean
    On Error GoTo Error_Handler
    Dim oQrys                 As Object
    Dim oQry                  As Access.AccessObject

    Set oQrys = CurrentData.AllQueries

    For Each oQry In oQrys    'Loop all the queries
        If oQry.IsLoaded = True Then 'check if it is open
            DoCmd.Close acQuery, oQry.Name, acSaveNo
        End If
    Next oQry
    
    CloseAllOpenQueries = True

Error_Handler_Exit:
    On Error Resume Next
    Set oQry = Nothing
    Set oQrys = Nothing
    Exit Function

Error_Handler:
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Source: CloseAllOpenQueries" & vbCrLf & _
           "Error Number: " & Err.Number & 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 Function

Usage Example(s)

Then to use the function we simply do:

Call CloseAllOpenQueries

Or

If CloseAllOpenQueries= True Then
    '...
End If

 

Useful Resources