2011-02-15 71 views
2

我試圖在Excel中採用少量數據(大約200個字段),並從SQL中用每個項目的where子句中的該字段檢索數據。從Excel 2007中查詢SQL並返回多個值

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 

我希望能夠找回,在Excel中(希望無需編寫任何額外的代碼本身 - 也許一個簡單的Excel ODBC或查詢的SQL連接,這樣我的數據最終會這樣對excel文件:

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

我不知道如果我解釋自己不夠清楚....

我使用Excel 2007和我也有2010亂扔某處SQL爲SQL Server 2000 。

謝謝!

+0

便便。這些例子並沒有表明我希望他們的方式...... – RogueSpear00 2011-02-15 23:08:21

+0

你想在Excel中使用日期和ID從SQL Server獲取姓名和電話,這是否正確?你對ADO有什麼看法? – Fionnuala 2011-02-15 23:11:32

回答

5

ADO,恐怕。

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 
-3

除非有充分的理由不在代碼中這樣做,否則應該使用代碼而不是sql。