ID: Q117644
The information in this article applies to:
In Microsoft Excel, if you are using the Visual Basic, Applications Edition SQLRetrieve command, and you want each column of results to be declared as a named range on the worksheet, you can set the "NamedRngLogical" argument to TRUE.
The name of each range is the field name of a column's result set. The syntax for the SQLRetrieve statement is as follows:
   SQLRetrieve(ConnectionNum, DestinationRef, MaxColumns, MaxRows,
     ColNamesLogical, RowNumsLogical, NamedRngLogical,
     FetchFirstLogical)
NOTE: The information in this article also applies to the Microsoft Excel 4.0 command SQL.EXEC.QUERY.
Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability and/or fitness for a particular purpose. This article assumes that you are familiar with the programming language being demonstrated and the tools used to create and debug procedures. Microsoft support professionals can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific needs. If you have limited programming experience, you may want to contact the Microsoft fee-based consulting line at (800) 936-5200. For more information about the support options available from Microsoft, please see the following page on the World Wide Web:
   http://www.microsoft.com/support/supportnet/refguide/
The following sample Visual Basic code uses the CUSTOMER.DBF file included with the sample data source NWind and assumes that:
1. The NWind ODBC driver is installed and points to the Windows or a shared
   MSAPPS\MSQUERY directory.
   EXCEL\LIBRARY\MSQUERY directory, under the TOOLS-REFERENCES menu.
1. In a new module sheet, enter in the following code:
      Sub GetData()
         ' To define the ranges for the column names in the workbook to 
         ' which the data is returned, use the following macro:
         Dim DestRange As Object
         Dim Chan, NumCols, NumRows As Variant
         Dim i As Integer
         Set DestRange = ThisWorkbook.Sheets("Sheet1").Range("A1")
         Chan = SQLOpen("DSN=NWind;FIL=dBase4;")
         ' Enter the following statement on a single line.
         NumCols = SQLExecQuery(Chan, "SELECT customer.CONTACT, " & _
           "customer.COMPANY FROM customer.dbf")
         NumRows = SQLRetrieve(Chan, DestRange, , , True)
         SQLClose(Chan)
         DestRange.Resize(NumRows + 1, NumCols).CreateNames Top:=True, _
            Left:=False
      End Sub
3. From the Tools menu, choose Macros, and then select the GetData macro.
Additional query words: 5.00 5.00a 5.00c 7.00
Keywords          : kbcode kbprg xlquery SynFnc 
Version           : WINDOWS:5.0,5.0c,7.0; MACINTOSH:5.0,5.0a
Platform          : MACINTOSH WINDOWS
Issue type        : kbhowtoLast Reviewed: May 17, 1999