如何将表从另一个访问数据库导出到Excel

时间:2014-10-27 14:43:24

标签: access-vba export-to-excel

我有一个只有表单和代码的前端访问数据库和一个包含所有数据表的后端访问数据库。我创建了一个临时访问数据库来执行所有必需的计算。在前端数据库的表单中,我有一个按钮,单击该按钮时,应该在临时数据库中输出一个表来表示excel。当我尝试使用docmd.outputto或docmd.transferspreadsheet时,我得到相同的错误#3011 - Microsoft Access数据库引擎找不到该对象。我是否需要尝试使用其他命令导出表格,或者我尝试做一些甚至不可能的事情?

Sub expottbl()
On Error GoTo Err_handle

Dim rstable As DAO.Recordset
Dim rsplan As DAO.Recordset
Dim ppath As String
dim tmpdb As DAO.Database
dim bedb As DAO.Database
dim wrkacc As DAO.Workspace

Set wrkacc = DBEngine(0)
Set tmpdb = wrkacc.OpenDatabase(tmppath)
ppath = “c:/my documents"

‘check for open file
If IsXLBookOpen(ppath) = True Then
MsgBox "Excel workbook is being used by another user. file cannot be exported"
rstable.Close: Set rstable = Nothing
rsplan.Close: Set rsplan = Nothing
tmpdb.Close
wrkacc.Close
Set tmpdb = Nothing
Set wrkacc = Nothing
Exit Sub
End If
rstable.Close: Set rstable = Nothing
rsplan.Close: Set rsplan = Nothing

‘export  table    
DoCmd.SetWarnings False
‘outputto option
DoCmd.OutputTo acOutputTable, "calc_tbl", acFormatXLSX, ppath, False, "", 0

 ‘transferspreadsheet option
  DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "calc_tbl", ppath, False

 MsgBox strloc & " file exported to:" & vbCrLf & ppath, vbInformation, ""
DoCmd.SetWarnings True

Set tmpdb = Nothing
Set wrkacc = Nothing

Exit Sub

exit_handle: 'exit due to error
Exit Sub

Err_handle: 'error info
MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
Err.Number & vbCrLf & "Error Description: " & _
Err.Description, vbCritical, "An Error has Occured!"
Resume exit_handle

End Sub