如何用VBA语言把EXCEL导入ACCESS中
时间: 2023-01-11 11:55:36 浏览: 511
为了在 Excel 中使用 VBA 将数据导入 Access,您需要执行以下步骤:
1. 在 Excel 中打开 VBA 编辑器。
2. 在编辑器中,在左侧资源管理器中双击 “模块”。
3. 现在,在模块窗口中输入以下代码:
```
Sub ExportToAccess()
' Declare variables
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strFile As String
Dim strCon As String
Dim strSQL As String
' Prompt user for database location
strFile = InputBox("Enter the database file location", "Database Location")
' Set connection string
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile
' Create connection
Set cn = New ADODB.Connection
cn.Open strCon
' Create recordset
Set rs = New ADODB.Recordset
' Set SQL string
strSQL = "SELECT * FROM [Sheet1$]"
' Open recordset
rs.Open strSQL, cn, adOpenKeyset, adLockOptimistic
' Loop through each record
Do While Not rs.EOF
' Add data to table
CurrentDb.Execute "INSERT INTO Table1 (Field1, Field2) VALUES ('" & rs!Field1 & "', '" & rs!Field2 & "')"
' Move to next record
rs.MoveNext
Loop
' Close recordset and connection
rs.Close
cn.Close
End Sub
```
4. 现在,您只需运行此代码即可从 Excel 将数据导入 Access。
注意:在上述代码中,您可能需要更改表名,以及要导入的字段和列的名称。
阅读全文
相关推荐















