(1条消息) Excel中VBA编程学习笔记(十六)
【例1】使用Connection的Execute的方法
数据库格式:
Sub test()
Dim conString$, sqlString$
Dim cnn, rst
Set cnn = CreateObject("ADODB.Connection")
Set rst = CreateObject("ADODB.Recordset")
Dim i%, sex$, Address$, Name$, birthDay$
conString = "provider=Microsoft.ace.OLEDB.12.0;Data Source=" & ThisWorkbook.Path & "\test.accdb;"
cnn.Open conString
sqlString = "update students set sSex='男'"
cnn.Execute sqlString
MsgBox "更新成功"
cnn.Close
End Sub
- 使用RecordSet
数据库字段如下:
Sub exercise()
Dim cnn, rst
Set cnn = CreateObject("ADODB.connection")
Set rst = CreateObject("ADODB.recordset")
Dim sqlStr$, conStr$
conStr$ = "provider=Microsoft.Ace.OLEDB.12.0;Data Source=" & ThisWorkbook.Path & "\test.mdb"
sqlStr = "select * from students where 总分 <160"
cnn.Open conStr$
rst.Open sqlStr, cnn, adOpenDynamic, adLockOptimistic
Do Until rst.EOF
rst("总分") = 160
rst.MoveNext
Loop
cnn.Close
End Sub
【例3】从excel获取批量写入ACCESS数据库
数据库字段如下:
Execel数据如下:
Sub exercise()
Dim cnn ', rst
Set cnn = CreateObject("ADODB.connection")
'Set rst = CreateObject("ADODB.recordset")
Dim rst As New ADODB.Recordset
Dim sqlStr$, conStr$, Count%
conStr$ = "provider=Microsoft.Ace.OLEDB.12.0;Data Source=" & ThisWorkbook.Path & "\test.accdb"
sqlStr = "insert into students(sName,sSex,sAddress,birthDay) select 姓名, 性别, 地址, 出生日期 from [excel 8.0;database=" & ThisWorkbook.FullName & "].[sheet2$]"
cnn.Open conStr$
cnn.Execute sqlStr, Count
MsgBox "更新了" & Count & "条结果"
cnn.Close
End Sub
注:上面方式对于未打开的工作薄也可以获取数据.红色加粗部分标注的Excel 8.0随着不同的office版本需要做相应的改变。