Add Method (QueryTables Collection)

Applies To

QueryTables collection object.

Description

Creates a new query table. Returns a QueryTable object that represents the new query table.

Syntax

expression.Add(Connection, Destination, Sql)

expression Required. An expression that returns a QueryTables object.

Connection Required Variant. The data source for the query table. Can be one of the following:

  • A string containing an ODBC connection string.
  • A QueryTable object from which the query information is initially copied, including the connection string and the SQL text, but not including the Destination range. Specifying a QueryTable object causes the Sql argument to be ignored.
  • A DAO RecordSet object. Data is read from the DAO recordset. Microsoft Excel retains the DAO recordset until the query table is deleted or the connection is changed. The resulting query table cannot be edited.
  • A Web query. A string in the form "URL;<url>", where "URL;" is required but not localized and the rest of the string is used for the URL of the Web query.
  • Data Finder. A string in the form "FINDER;<data finder file path>" where "FINDER;" is required but not localized. The rest of the string is the path and file name of a Data Finder file (*.dqy or *.iqy). The file is read when the Add method is run; subsequent calls to the Connection property of the query table will return strings beginning with "ODBC;" or "URL;" as appropriate.
Destination Required Range. The cell in the upper-left corner of the query table destination range (the range where the resulting query table will be placed). The destination range must be on the worksheet that contains the QueryTables object specified by expression.

Sql Optional Variant. The SQL query string to be run on the ODBC data source. This argument is optional when you're using an ODBC data source (if you don't specify it here, you should set it by using the Sql property of the query table before the table is refreshed). This argument cannot be used when a QueryTable object or a DAO Recordset object is specified as the data source.

Remarks

A query created by this method isn't run until the Refresh method is called.

Example

This example creates a new query table.

sqlstring = "select 96Sales.totals from 96Sales where profit < 5"
connstring = _
    "ODBC;DSN=96SalesData;UID=Rep21;PWD=NUyHwYQI;Database=96Sales"
With ActiveSheet.QueryTables.Add(Connection:=connstring, _
        Destination:=Range("B1"), Sql:=sqlstring)
    .Refresh
End With