gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:46:52 25 4
gpt4 key购买 nike

我对 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”?

最佳答案

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

ActiveWorkbook.Queries("Query1").Delete

关于sql - 使用 Vba 从 Excel 工作簿中删除查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44827417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com