以下实例的内容是,通过VBA读取SQL数据库,将结果填充到Excel表。
希望本文对您有所帮助。
Dim i As Integer, j As Integer, sht As Worksheet 'i,j为整数变量;sht 为excel工作表对象变量,指向某一工作表
Dim cn As New ADODB.Connection '定义数据链接对象 ,保存连接数据库信息;请先添加ADO引用
Dim rs As New ADODB.Recordset '定义记录集对象,保存数据表
Dim strCn As String, strSQL As String '字符串变量
strCn = "Provider=sqloledb;Server=(local);Database=tywk;Uid=sa;Pwd=wkserver9;" '定义数据库链接字符串
cn.Open strCn
FINALROW = Cells(65535, 1).End(xlUp).Row
Set sht = ThisWorkbook.Worksheets("更新数据库")
For i = 2 To FINALROW '循环开始
strSQL = "insert into tywk.dbo.表名 values('" & sht.Cells(i, 1) _
& "' ,'" & sht.Cells(i, 2) & "' ,'" & sht.Cells(i, 3) & "' ,'" & sht.Cells(i, 4) _
& "' ,'" & sht.Cells(i, 5) & "' ,'" & sht.Cells(i, 6) & "' ,'" & sht.Cells(i, 7) _
& "' ,'" & sht.Cells(i, 8) & "' ,'" & sht.Cells(i, 9) & "' ,'" & sht.Cells(i, 10) _
& "' ,'" & sht.Cells(i, 11) & "' ,'" & sht.Cells(i, 12) & "' ,'" & sht.Cells(i, 13) _
& "' ,'" & sht.Cells(i, 14) & "' ,'" & sht.Cells(i, 15) & "' ,'" & sht.Cells(i, 16) _
& "' ,'" & sht.Cells(i, 17) & "' ,'" & sht.Cells(i, 18) & "');"
cn.Execute strSQL
Next
MsgBox "保存成功"
cn.Close