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

VBA連線SQL資料庫的方法

Dim cnn As Object
Dim rs As Object
Set rs = CreateObject("ADODB.RecordSet")
Set cnn = CreateObject("ADODB.Connection")
Dim strSQL As String
Dim cnnStr As String
'  Set cnn = New ADODB.Connection ﹚Microsoft activeX data object 2.1
  
   cnn.ConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=True;User ID=**;Password=**;Initial Catalog=**;Data Source=**;Connect Timeout=5;"
   strSQL = "select top 10 * from code_map"
   cnn.Open cnn.ConnectionString
   rs.Open strSQL, cnn




Set sht = ThisWorkbook.Worksheets("sheet3")
Do While Not rs.EOF
    i = i + 1
    sht.Cells(i, 1) = rs(1)
    sht.Cells(i, 2) = rs(3)
    sht.Cells(i, 3) = rs(5)
    sht.Cells(i, 4) = rs(6)
    rs.MoveNext
  
Loop
rs.Close