Search code examples
sqlexcel-2007database-connectivity

Query SQL From Excel 2007 And Return Several Values


I'm attempting to take a small amount of data, about 200 fields in Excel and retreive data from SQL with that field in the where clause for each item.

TABLE:

ID  Name    Phone
1   Test1   1234
2   Test2   1235
3   Test3   1236


Excel:
Date   ID
2/1/11 1
2/1/11 2
2/1/11 3

I want to be able to retrieve, within excel (hopefully without writing any additional code per se - maybe a simply Excel ODBC or SQL connection with a query. So my data would end up as such on the Excel Document:

Excel:
Date   ID  Name    Phone 
2/1/11 1   Test1   1234
2/1/11 2   Test2   1235
2/1/11 3   Test3   1236

I'm not sure if I'm explaining myself clearly enough....

I'm using Excel 2007 and I also have 2010 laying around somewhere. SQL is SQL Server 2000.

Thanks!


Solution

  • ADO, I am afraid.

    Dim cn As Object
    Dim rs As Object
    Dim strFile As String
    Dim strCon As String
    Dim strSQL As String
    Dim s As String
    Dim i As Integer, j As Integer
    
    ''This is not the best way to refer to the workbook
    ''you want, but it is very convenient for notes
    ''It is probably best to use the name of the workbook.
    
    strFile = ActiveWorkbook.FullName
    
    ''Note that if HDR=No, F1,F2 etc are used for column names,
    ''if HDR=Yes, the names in the first row of the range
    ''can be used.
    ''This is the Jet 4 connection string, you can get more
    ''here : http://www.connectionstrings.com/excel
    
    strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
        & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
    
    ''Late binding, so no reference is needed
    
    Set cn = CreateObject("ADODB.Connection")
    Set rs = CreateObject("ADODB.Recordset")
    
    
    cn.Open strCon
    
    strSQL = "SELECT * " _
           & "FROM [Sheet1$] a " _
           & "LEFT JOIN " _
           & "[ODBC;Driver={SQL Server Native Client 10.0};" _
           & "Server=servername;Database=test;" _
           & "Trusted_Connection=yes].tbl b " _
           & "ON a.[Id]=b.[Id] "
    
    rs.Open strSQL, cn, 3, 3
    
    
    ''Pick a suitable empty worksheet for the results
    Worksheets("Sheet3").Cells(2, 1).CopyFromRecordset rs
    
    ''Tidy up
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing