Delete a query from excel workbook with Vba
32,978
Try adding the following line.
The Activeworkbook.Queries() takes a Name or Index
ActiveWorkbook.Queries("Query1").Delete
Author by
dgard
Updated on September 18, 2021Comments
-
dgard over 2 years
I am pretty new to VBA and am learning how to add connections to databases in excel. I currently have a macro that creates a query called "Query1" it then queries my database and returns the correct table. I would like to be able to delete the query after the table is output to the excel sheet so that I can run the macro again with slightly modified conditions eg different dates.
Sub Macro2() ' ' Macro2 Macro ' ActiveWorkbook.Queries.Add Name:="Query1", Formula:= _ "let" & Chr(13) & "" & Chr(10) & " Source = Odbc.Query(""dsn=Database"", ""SELECT DISTINCT c.IP_TREND_VALUE AS """"PRODUCT"""", c.IP_TREND_TIME , s.IP_TREND_TIME AS TIMES, s.IP_TREND_VALUE AS """"Wttotal""""#(lf)FROM """"Product"""" AS c , """"wtTotal"""" as s#(lf)#(lf)Where #(lf)#(tab) c.TIME Between '1-JUN-17 05:59:00' AND '2-" & _ "JUN-17 05:59:00' AND c.TIME = s.IME#(lf)"")" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " Source" & _ "" With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _ "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Query1" _ , Destination:=Range("$A$1")).QueryTable .CommandType = xlCmdSql .CommandText = Array("SELECT * FROM [Query1]") .RowNumbers = False .FillAdjacentFormulas = False .PreserveFormatting = True .RefreshOnFileOpen = False .BackgroundQuery = True .RefreshStyle = xlInsertDeleteCells .SavePassword = False .SaveData = True .AdjustColumnWidth = True .RefreshPeriod = 0 .PreserveColumnInfo = True .ListObject.DisplayName = "Query1" .Refresh BackgroundQuery:=False End With End Sub
I would like to add something like the following after the table is placed into the worksheet
ActiveWorkbook.Queries.Delete = Name: = "Query1"
But obviously this doesn't exist. How can I remove the query or make it so that the macro can be run without having to delete "Query1"?