Excel讀取資料庫表,excel讀取資料庫

來源:互聯網
上載者:User

Excel讀取資料庫表,excel讀取資料庫

下面的代碼用於一般情況下用Excel宏讀取資料庫的表欄位

Public Sub getdata()    Dim cnn As New ADODB.Connection, sh As Worksheet    Dim rs As New ADODB.Recordset    Dim cnnStr As String, SQL As String    cnnStr = "Provider=SQLOLEDB;Initial Catalog=BI" & ";User ID=sa" & ";Password=Aa123456" & ";Data Source=172.16.0.73"    cnn.ConnectionString = cnnStr    cnn.Open    SQL = "SELECT * from dbo.tt"     MsgBox "執行查詢資料開始: " & SQL    Set rs = cnn.Execute(SQL)    For col = 0 To rs.Fields.Count - 1        Sheets("Sheet2").Range("A1").Offset(0, col).Value = rs.Fields(col).Name    Next    Sheets("Sheet2").Range("A1").Offset(1, 0).CopyFromRecordset rs    rs.Close    MsgBox "執行查詢結束!"    Set rs = Nothing    cnn.Close    Set cnn = NothingEnd Sub

對代碼的說明:
Data Source:資料庫IP
Catalog:資料庫名
User ID:使用者名稱
Password:資料庫密碼
SQL :SQL語句,通常是直接讀取某個表
執行過程會有兩個快顯視窗,點擊確認即可。
最後資料會寫入當前Excel檔案的Sheet2中

要執行上面的代碼還需要給Excel設定一下:
大概是Library的,記不清了,後面想起來再更新此文。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.