将每个访问表导出到单个工作簿

时间:2016-09-02 13:26:08

标签: vba ms-access export-to-excel ms-access-2013

我一直在使用这种语法将数据库中的每个表导出到一个excel工作簿,但现在我需要将每个表导出到它自己的工作簿。如何调整它以将每个表导出到它自己的工作簿?

Sub ExportToExcel()
  Dim td As DAO.TableDef, db As DAO.Database
  Dim out_file As String

  out_file = "C:\fromaccess.xlsx"

  Set db = CurrentDb()
    For Each td in db.TableDefs
      If Left(td.Name, 4) = "MSys" Then
        'Do Nothing
      Else
        DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, td.Name, out_file, True, Replace(td.Name, "dbo_","")
      End If
      Next
End Sub

修改
我尝试了@ HA560的建议,但得到错误

  

运行时错误'91':
  对象变量或未设置块变量

这是更新的代码:

Sub ExportToExcel()
Dim td As DAO.TableDef, db As DAO.Database
Dim out_file As String
Dim xl As Excel.Application

out_file = "C:\fromaccess.xlsx"

Set db = CurrentDb()
For Each td in db.TableDefs
xl.Workbooks.Add  
If Left(td.Name, 4) = "MSys" Then
    'Do Nothing
  Else
    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, td.Name, out_file, True, Replace(td.Name, "dbo_","")
  End If
  Next
End Sub

2 个答案:

答案 0 :(得分:0)

一个长的,包括三个程序。运行后,您应该在即时窗口中有一个表名列表和TRUE / FALSE,说明导出是否成功。

ExportAll - 主要程序。
CreateXL - 这会创建一个Excel实例。它使用后期绑定,因此无需设置引用。

QueryExportToXL - 这是导出表格的代码。我没有使用TransferSpreadsheet,因为我更喜欢控制。

  • 您需要将工作表引用传递给函数。
  • 您可以将查询名称或记录集传递给该函数。
  • 您可以传递替代工作表名称。
  • 要粘贴的默认单元格是A1,但您可以更改此内容。
  • 默认情况下,它会调整列宽以适应。
  • 您可以传递一组标题名称而不是字段名称。

那里没有太多的错误处理 - 例如传递不同数量的标题名称而不是字段,给出非法的工作表名称。
它需要工作:))

Public Sub ExportAll()

    Dim db As DAO.Database
    Dim tdf As DAO.TableDef
    Dim rst As DAO.Recordset
    Dim oXL As Object
    Dim oWrkBk As Object

    Set db = CurrentDb

    'Create instance of Excel.
    Set oXL = CreateXL

    For Each tdf In db.TableDefs
        If Left(tdf.Name, 4) <> "MSys" Then

            'Create workbook with single sheet.
            Set oWrkBk = oXL.WorkBooks.Add(-4167) 'xlWBATWorksheet

            'Open the table recordset.
            Set rst = tdf.OpenRecordset

            'In the immediate window display table name and TRUE/FALSE if exported successfully.
            Debug.Print tdf.Name & " - " & QueryExportToXL(oWrkBk.worksheets(1), , rst, tdf.Name)

            'Save and close the workbook.
            oWrkBk.SaveAs "<path to folder>" & tdf.Name
            oWrkBk.Close

        End If
    Next tdf

End Sub

'----------------------------------------------------------------------------------
' Procedure : CreateXL
' Author    : Darren Bartrup-Cook
' Date      : 02/10/2014
' Purpose   : Creates an instance of Excel and passes the reference back.
'-----------------------------------------------------------------------------------
Public Function CreateXL(Optional bVisible As Boolean = True) As Object

    Dim oTmpXL As Object

    '''''''''''''''''''''''''''''''''''''''''''''''''''''
    'Defer error trapping in case Excel is not running. '
    '''''''''''''''''''''''''''''''''''''''''''''''''''''
    On Error Resume Next
    Set oTmpXL = GetObject(, "Excel.Application")

    '''''''''''''''''''''''''''''''''''''''''''''''''''''''
    'If an error occurs then create an instance of Excel. '
    'Reinstate error handling.                            '
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''
    If Err.Number <> 0 Then
        Err.Clear
        On Error GoTo ERROR_HANDLER
        Set oTmpXL = CreateObject("Excel.Application")
    End If

    oTmpXL.Visible = bVisible
    Set CreateXL = oTmpXL

    On Error GoTo 0
    Exit Function

ERROR_HANDLER:
    Select Case Err.Number

        Case Else
            MsgBox "Error " & Err.Number & vbCr & _
                " (" & Err.Description & ") in procedure CreateXL."
            Err.Clear
    End Select


End Function


'----------------------------------------------------------------------------------
' Procedure : QueryExportToXL
' Author    : Darren Bartrup-Cook
' Date      : 26/08/2014
' Purpose   : Exports a named query or recordset to Excel.
'-----------------------------------------------------------------------------------
Public Function QueryExportToXL(wrkSht As Object, Optional sQueryName As String, _
                                                  Optional rst As DAO.Recordset, _
                                                  Optional SheetName As String, _
                                                  Optional rStartCell As Object, _
                                                  Optional AutoFitCols As Boolean = True, _
                                                  Optional colHeadings As Collection) As Boolean

    Dim db As DAO.Database
    Dim prm As DAO.Parameter
    Dim qdf As DAO.QueryDef
    Dim fld As DAO.Field
    Dim oXLCell As Object
    Dim vHeading As Variant

    On Error GoTo ERROR_HANDLER

    If sQueryName <> "" And rst Is Nothing Then

        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        'Open the query recordset.                               '
        'Any parameters in the query need to be evaluated first. '
        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        Set db = CurrentDb
        Set qdf = db.QueryDefs(sQueryName)
        For Each prm In qdf.Parameters
            prm.Value = Eval(prm.Name)
        Next prm
        Set rst = qdf.OpenRecordset
    End If

    If rStartCell Is Nothing Then
        Set rStartCell = wrkSht.cells(1, 1)
    Else
        If rStartCell.Parent.Name <> wrkSht.Name Then
            Err.Raise 4000, , "Incorrect Start Cell parent."
        End If
    End If


    If Not rst.BOF And Not rst.EOF Then
        With wrkSht
            Set oXLCell = rStartCell

            ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            'Paste the field names from the query into row 1 of the sheet. '
            'Or the alternative field names provided in a collection.      '
            ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            If colHeadings Is Nothing Then
                For Each fld In rst.Fields
                    oXLCell.Value = fld.Name
                    Set oXLCell = oXLCell.Offset(, 1)
                Next fld
            Else
                For Each vHeading In colHeadings
                    oXLCell.Value = vHeading
                    Set oXLCell = oXLCell.Offset(, 1)
                Next vHeading
            End If

            ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            'Paste the records from the query into row 2 of the sheet. '
            ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            Set oXLCell = rStartCell.Offset(1, 0)
            oXLCell.copyfromrecordset rst
            If AutoFitCols Then
                .Columns.Autofit
            End If

            If SheetName <> "" Then
                .Name = SheetName
            End If

            '''''''''''''''''''''''''''''''''''''''''''
            'TO DO: Has recordset imported correctly? '
            '''''''''''''''''''''''''''''''''''''''''''
            QueryExportToXL = True

        End With
    Else

        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        'There are no records to export, so the export has failed. '
        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        QueryExportToXL = False
    End If

    Set db = Nothing

    On Error GoTo 0
    Exit Function

ERROR_HANDLER:
    Select Case Err.Number

        Case Else
            MsgBox "Error " & Err.Number & vbCr & _
                " (" & Err.Description & ") in procedure QueryExportToXL."
            Err.Clear
            Resume
    End Select

End Function

答案 1 :(得分:-1)

每次使用后workbooks.add()方法...... out_file=activeworkbook.path