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

balp4ylt  于 2022-11-26  发布在  其他
关注(0)|答案(3)|浏览(378)

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

ctrmrzij

ctrmrzij1#

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

ActiveWorkbook.Queries("Query1").Delete
xcitsw88

xcitsw882#

试试这个:

For Each Worksheet In ThisWorkbook.Worksheets
    Qcount = Worksheet.QueryTables.Count
    If Qcount > 0 Then
        For Each QueryTable In ws.QueryTables
            QueryTable.Delete
        Next
    End If
Next Worksheet
lb3vh1jj

lb3vh1jj3#

删除Excel工作簿中的所有查询

Dim Qcount As Integer
Dim i As Integer

Qcount = ActiveWorkbook.Queries.Count

For i = Qcount To 1 Step -1
      ActiveWorkbook.Queries(i).Delete
Next

相关问题