请教怎么在access中用VBA导入excel数据到access库

方法一:在eccel VBA编辑器编写代码,使用FOR循环导入:

Sub 利用Excel的VBA将数据写入Access()

'定义ADODB 连接Access数据库

Dim Cnn As New ADODB.Connection

Dim Rs As New ADODB.Recordset

Dim strCon As String

Dim strFileName As String '数据库文件名

strFileName = InputBox("请输入文件路径及文件名:", "Excel传递数据至Access", "E:\ExcelTest\Staff.mdb")

'连接字符串,我这里是Access2010,所提供者参数为:Provider=Microsoft.ACE.OLEDB.12.0;

'如果此参数不能使用,根据自己的电脑修改这个字符串

'至于连接至的数据库名,根据自己的电脑修改,或用一个对话框或其他方式将此值传递进程序

strCon = "provider=Microsoft.jet.OLEDB.4.0;" _

& "Data Source=" & strFileName & ";"

Cnn.Open strCon

Rs.ActiveConnection = Cnn

Rs.LockType = adLockOptimistic

Rs.Open "Employee" '假设表为Employee

'定义Excel表中的数据区域以写入Access

Dim Sht As Worksheet

Dim Rn As Long

Dim Cn As Long

Set Sht = ThisWorkbook.Sheets("Sheet1")

'假设将 Sheet1 表的 2-6行的1、2、3列写入Access表

For Rn = 2 To 6

Rs.AddNew

Rs!num = Sht.Cells(Rn, 1) ’num,name,department是数据库中指定表的字段

Rs!Name = Sht.Cells(Rn, 2)

Rs!department = Sht.Cells(Rn, 3)

Rs.Update

Next Rn

MsgBox "完成!"

Rs.Close

Cnn.Close

Set Rs = Nothing

Set Cnn = Nothing

Set Sht = Nothing

End Sub

方法二:在access VBA编辑器中编写代码

Sub ExcelToAccess()

DoCmd.TransferSpreadsheet acImport, , "Staff", "E:\ExcelTest\Employee.xls", True, "Sheet1!" ‘DoCmd.TransferSpreadsheet是access编辑器中函数

End Sub