本文逐步介紹如何將數(shù)據(jù)從 Microsoft SQL Server 附帶的示例數(shù)據(jù)庫 Pubs 中導(dǎo)入 Microsoft Excel。
ActiveX 數(shù)據(jù)對象 (ADO) 可用來訪問任意類型的數(shù)據(jù)源。它是具有少數(shù)幾個對象的平面對象模型。ADO 對象模型中的主要對象有:
對象 說明--------------------------------------------------------------------------Connection 指示到數(shù)據(jù)源的連接。Recordset 指示所提取的數(shù)據(jù)。Command 指示需要執(zhí)行的存儲過程或 SQL 語句。
盡管使用 ADO 返回記錄集有很多種方法,但本文主要介紹 Connection 和 Recordset 對象。
要求
必須具有運(yùn)行 Microsoft SQL Server 且包含 Pubs 數(shù)據(jù)庫的本地服務(wù)器。
Microsoft 建議您掌握以下幾個方面的知識:
• | 在 Office 程序中創(chuàng)建 Visual Basic for Applications 過程。 |
• | 使用 Object 變量。 |
• | 使用 Excel 對象。 |
• | 關(guān)系數(shù)據(jù)庫管理系統(tǒng) (RDBMS) 概念。 |
• | 結(jié)構(gòu)化查詢語言 (SQL) SELECT 語句 |
引用 ADO 對象庫
1. | 啟動 Excel。打開一個新工作簿,然后將其保存為 SQLExtract.xls。 |
2. | 啟動 Visual Basic 編輯器并選擇您的 VBA 項(xiàng)目。 |
3. | 在工具菜單上,單擊引用。 |
4. | 單擊以選中最新版本的 Microsoft ActiveX 數(shù)據(jù)對象庫的復(fù)選框。 |
創(chuàng)建連接
1. | 在項(xiàng)目中插入一個新模塊。 |
2. | 創(chuàng)建一個新的名為 DataExtract 的子過程。 |
3. | 鍵入或粘貼以下代碼:‘ Create a connection object.Dim cnPubs As ADODB.ConnectionSet cnPubs = New ADODB.Connection‘ Provide the connection string.Dim strConn As String‘Use the SQL Server OLE DB Provider.strConn = "PROVIDER=SQLOLEDB;"‘Connect to the Pubs database on the local server.strConn = strConn & "DATA SOURCE=(local);INITIAL CATALOG=pubs;"‘Use an integrated login.strConn = strConn & " INTEGRATED SECURITY=sspi;"‘Now open the connection.cnPubs.Open strConn
|
提取數(shù)據(jù)
鍵入或粘貼以下代碼以提取您的記錄:
‘ Create a recordset object.Dim rsPubs As ADODB.RecordsetSet rsPubs = New ADODB.RecordsetWith rsPubs ‘ Assign the Connection object. .ActiveConnection = cnPubs ‘ Extract the required records. .Open "SELECT * FROM Authors" ‘ Copy the records into cell A1 on Sheet1. Sheet1.Range("A1").CopyFromRecordset rsPubs ‘ Tidy up .CloseEnd WithcnPubs.CloseSet rsPubs = NothingSet cnPubs = Nothing
驗(yàn)證能否正常工作
1. | 運(yùn)行上述代碼。 |
2. | 切換到 Excel 并在工作簿的 Sheet1 中查看數(shù)據(jù)。 |
疑難解答
如果代碼似乎掛起并出現(xiàn)運(yùn)行時錯誤,則數(shù)據(jù)庫服務(wù)器可能已停機(jī)。您可以使用 ConnectionTimeout 屬性來控制返回運(yùn)行時錯誤所需的時間。請將此屬性的值設(shè)置為大于零。如果將該值設(shè)置為零,則連接將永遠(yuǎn)不會超時。默認(rèn)值是 15 秒。
通過搜索以下 Microsoft Web 站點(diǎn)可以找到其他代碼示例: