code to delete existing query

L

Legacy 15162

Guest
what would be the vba code to first see if a query exists, then to delete if true?
 

Excel Facts

Quick Sum
Select a range of cells. The total appears in bottom right of Excel screen. Right-click total to add Max, Min, Count, Average.
The following lines of code will delete the query if it exists, and do nothing if it doesn't.
Code:
    On Error Resume Next
    DoCmd.DeleteObject acQuery, "QueryName"
    On Error GoTo 0
 
Upvote 0
How about something like this:

Code:
Sub DeleteExistingQuery()
Dim db
Dim qdf
Dim QueryName
Dim Deleted As Boolean

    QueryName = InputBox("Please enter the name of the query you wish to delete:", "Delete existing query")

    If QueryName <> "" Then
        Set db = CurrentDb
        
        For Each qdf In db.QueryDefs
            If qdf.Name = QueryName Then
                db.QueryDefs.Delete qdf.Name
                Deleted = True
                Exit For
            End If
        Next
        
        If Deleted Then
            MsgBox QueryName & " succesfully deleted.", vbOKOnly + vbInformation, "Query deleted"
        Else
            MsgBox QueryName & " not found - check name and try again.", vbOKOnly + vbCritical, "Query not found"
        End If
        
    End If
End Sub
 
Upvote 0

Forum statistics

Threads
1,221,821
Messages
6,162,157
Members
451,750
Latest member
pnkundalia

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