使用Vba从Excel工作簿中删除查询

我对VBA很新颖,并且正在学习如何在Excel中添加连接到数据库。 我目前有一个macros创build一个名为“Query1”的查询,然后查询我的数据库并返回正确的表。 我希望能够将表格输出到Excel表格后删除查询,以便我可以稍微修改条件,例如不同的date再次运行macros。

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 

将表放入工作表后,我想添加如下内容

 ActiveWorkbook.Queries.Delete = Name: = "Query1" 

但显然这不存在。 如何删除查询或使其可以运行macros而不必删除“Query1”?

尝试添加以下行。
Activeworkbook.Queries()需要一个名称或索引

 ActiveWorkbook.Queries("Query1").Delete