5

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"?

3 Answers 3

7

Try adding the following line.
The Activeworkbook.Queries() takes a Name or Index

ActiveWorkbook.Queries("Query1").Delete
Sign up to request clarification or add additional context in comments.

1 Comment

But what if we need to delete only from the current sheet? Trying to do the same on ActiveSheet doesn't seem to work.
2

try this:

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

1 Comment

How can we remove the queries on the active WorkSHEET alone ?
1

Delete all Queries in an Excel Workbook using

Dim Qus As WorkbookQuery

For Each Qus In ActiveWorkbook.Queries
  Qus.Delete
Next

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.