1. 程式人生 > >Excel的VBA連線資料庫方法

Excel的VBA連線資料庫方法

Sub GetData()     
     Dim strConn As String, strSQL As String 
     Dim conn As ADODB.Connection 
     Dim ds As ADODB.Recordset 
     Dim col As Integer 

'清空電子表格的所有資料 
    Cells.Clear 

'連線資料庫的字串 
    strConn = "Provider=SQLOLEDB.1;Persist Security Info=True;User ID=name;Password=pwd;Initial Catalog=dataname;Data Source=servername" 

'查詢語句
     strSQL = "select * from table1" 
     Set conn = New ADODB.Connection 
     Set ds = New ADODB.Recordset 
'開啟資料庫連線
     conn.Open strConn 

     With ds 
'根據查詢語句獲得資料 
         .Open strSQL, conn 

'自動控制加入所有列標題
         For col = 0 To ds.Fields.Count - 1 
'請注意Offset(0, col)中的引數一定要正確噢
             Range("A1").Offset(0, col).Value = ds.Fields(col).Name 

         Next 

'加入所有行資料 
         Range("a1").Offset(1, 0).CopyFromRecordset ds 
     End With 

'以下是關閉資料庫連線和清空資源
     Set ds = Nothing 
     conn.Close 
     Set conn = Nothing 
End Sub 

做完上面的模組後,要呼叫它就要加入一個事件: 
'我這個是加入一個工作薄開啟時就執行GetData方法,也就是自動載入資料
Private Sub Workbook_Open() 
     Application.Run "GetData" 
End Sub