假设stu人员信息表(如下),数据存放在同目录下test.accdb文件,采用VBA代码方式对Access进行增、删、改、查操作,实现代码也是非常简单。
一、Excel连接Access
Dim conn As Object, rst As Object
Dim sql As String
Dim i As Integer
'数据库连接并打开数据库
Set conn = CreateObject("ADODB.Connection") '需引用ADO引擎
Set rst = CreateObject("ADODB.Recordset") '需引用Recordset数据集
conn.ConnectionString = "Provider=Microsoft.Ace.OleDB.12.0;Data Source=" &
_ThisWorkbook.Path & "test.accdb" 'ThisWorkbook.Path可以换做其它数据库路劲
conn.Open
二、将Excel数据插入到Access
For i = 2 To 5
sql = "INSERT INTO stu(姓名,性别,年龄,籍贯) values('" & Cells(i, 1) & "','" & Cells(i, 2) &
_"','" & Cells(i, 3) & "','" & Cells(i, 4) & "') "
conn.Execute sql
Next
三、通过Excel删除Access数据库记录
sql = "DELETE FROM stu where ID=2"
conn.Execute sql
四、通过Excel修改Access数据记录
sql = "update stu set 年龄=30 where ID=3"
conn.Execute sql
五、通过Excel获取Access数据
sql = "select * from stu"
rst.Open sql, conn
i = 1
Cells(i, 1) = "ID"
Cells(i, 2) = "姓名"
Cells(i, 3) = "性别"
Cells(i, 4) = "年龄"
Cells(i, 5) = "籍贯"
i = 2
Do While Not rst.EOF
Cells(i, 1) = rst.Fields("ID")
Cells(i, 2) = rst.Fields("姓名")
Cells(i, 3) = rst.Fields("性别")
Cells(i, 4) = rst.Fields("年龄")
Cells(i, 5) = rst.Fields("籍贯")
rst.MoveNext
i = i 1
Loop
rst.Close '关闭数据集
conn.Close '关闭数据库连接
评论 (0)