如何用VBA实现将access数据库中的表"导出数据"以execl表导出至路径C:\存储?
时间: 2024-03-16 08:42:21 浏览: 73
以下是将Access数据库中的表导出为Excel表格并保存到本地路径的 VBA 代码:
```
Sub ExportTableToExcel()
Dim db As DAO.Database
Dim tbl As DAO.TableDef
Dim xlApp As Object
Dim xlBook As Object
Dim xlSheet As Object
Dim rs As DAO.Recordset
Dim fld As DAO.Field
Dim i As Long, j As Long
Dim filePath As String
'设置Access数据库路径和表名
Set db = CurrentDb
Set tbl = db.TableDefs("导出数据")
'设置Excel应用程序和工作簿
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Sheets(1)
'复制表头
j = 1
For Each fld In tbl.Fields
xlSheet.Cells(1, j).Value = fld.Name
j = j + 1
Next fld
'复制表格数据
Set rs = tbl.OpenRecordset(dbOpenSnapshot)
i = 2
Do While Not rs.EOF
j = 1
For Each fld In rs.Fields
xlSheet.Cells(i, j).Value = fld.Value
j = j + 1
Next fld
i = i + 1
rs.MoveNext
Loop
'关闭数据库和记录集
rs.Close
Set rs = Nothing
db.Close
Set db = Nothing
'保存Excel文件到指定路径
filePath = "C:\存储\导出数据.xlsx"
xlBook.SaveAs filePath
'关闭Excel应用程序和工作簿
xlBook.Close
Set xlBook = Nothing
xlApp.Quit
Set xlApp = Nothing
MsgBox "导出成功!"
End Sub
```
使用方法:
1. 打开 Access 数据库,按下 Alt + F11 进入 VBA 编辑器;
2. 在 VBA 编辑器中,选择“插入”->“模块”;
3. 将上述代码复制粘贴到模块中;
4. 修改代码中的表名和保存路径;
5. 运行代码,Excel 文件将保存到指定路径中。
阅读全文