SQLExecQuery Function

SQLExecQuery Function

Office 2007

It is recommended that you use the objects, methods, and properties in the Microsoft ActiveX Data Objects (ADO) library instead of SQLOpen and the other ODBC functions in the Xlodbc.xla add-in.

SQLExecQuery executes a query on a data source with a connection that has been established with SQLOpen.

SQLExecQuery executes only the query. Use SQLRetrieve or SQLRetrieveToFile to get the results.

This function is contained in the Xlodbc.xla add-in. Before you use the function, you must establish a reference to the add-in by using the References command (on the Tools menu) in the Visual Basic Editor.

SQLExecQuery(ConnectionNum, QueryText)

Return Value

The value returned by SQLExecQuery depends on the SQL statement, as shown in the following table.

SQL statementReturn value
SELECTThe number of columns in the result set
UPDATE, INSERT, or DELETEThe number of rows affected by the statement
Any other valid SQL statement0 (zero)

If SQLExecQuery is unable to execute the query on the specified data source, it returns Error 2042.

If ConnectionNum isn’t valid, SQLExecQuery returns Error 2015.


Before calling SQLExecQuery, you must establish a connection to a data source by using SQLOpen. The unique connection ID returned by SQLOpen is used by SQLExecQuery to send queries to the data source.

If you call SQLExecQuery using a previously used connection ID, any pending results on that connection are replaced by the new results.


This example runs a query on the Northwind database. The result of the query, displayed on Sheet1, is a list of all products that are currently on order.

databaseName = "Northwind"
queryString = _
    "SELECT * FROM product.dbf WHERE (product.ON_ORDER<>0)"
chan = SQLOpen("DSN=" & databaseName)
SQLExecQuery chan, queryString
Set output = Worksheets("Sheet1").Range("A1")
SQLRetrieve chan, output, , , True
SQLClose chan

© 2015 Microsoft