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

时间:2017-06-29 14:05:32

标签: sql excel vba odbc

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

 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"

但显然这不存在。如何删除查询或使其成为可以运行宏而无需删除“Query1”?

1 个答案:

答案 0 :(得分:4)

尝试添加以下行。
Activeworkbook.Queries()采用名称或索引

ActiveWorkbook.Queries("Query1").Delete