Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

Exporting All Access Tables into Excel WorkBook

Introduction.

We already learned how to use MS Access live data in Excel earlier. Another VBA-based procedure was created to export the Table/Query data in the current version of the Excel Workbook.  The main advantage, when the exported data is saved in the current version of Excel Workbook, the default Theme of data formatting features is automatically applied, rather than the Excel 2003 formatting used by the acSpreadSheetTypeExcel3 to 9 range of Parameters, by default.

We could export filtered data through multiple query criteria and save the data sets in separate Worksheets in a single WorkBook.  A modified version of this method filters data on multiple criteria and exports the records into separate Workbooks too. 

Excel Tools are superb for Worksheet analysis, Charts, and Reports with automation features. But, Excel is not made as a Database Management System.  When the history of data becomes crucial for decision making, budget projections, business target settings and so on Excel users will look for a better database management system, like MS Access with flexibility.

But, exporting the complete set of Tables from Access to Excel Workbook may not be an everyday requirement.

Exporting All Access Tables Into Excel Workbook.

But, for some reason or the other, if it becomes necessary, you can use the VBA Program given below.

The VBA Program ExportAllTables2Excel()

Copy and Paste the Code given below into the Standard Module of your Project.

Public Sub ExportAllTables2Excel()
'----------------------------------------------------------------
'Program : ExportAllTables2Excel
'Purpose : Export All Access Tables into Excel WorkBook
'Author  : a.p.r. pillai
'Rights  : All Rights Reserved by www.msaccesstips.com
'Remarks : Creates separate WorkSheets for each Table
'        : in a single WorkBook.
'        : Table Name is Worksheet Name
'----------------------------------------------------------------
Dim db As Database
Dim xlsFileLoc As String
Dim xlsName As String
Dim xlsPath As String
Dim Tbl As TableDef
Dim tblName As String
Dim j As Integer
Dim wrkBook As Excel.Workbook

On Error GoTo Export2Excel_Err

xlsFileLoc = CurrentProject.Path & "\"
xlsName = "AllTables.xlsx"

xlsPath = xlsFileLoc & xlsName
    
If Len(Dir(xlsPath)) > 0 Then
    Kill xlsPath
End If

    Set wrkBook = Excel.Workbooks.Add
    wrkBook.SaveAs xlsPath
    wrkBook.Close
        
Set db = CurrentDb

j = 0
For Each Tbl In db.TableDefs
    tblName = Tbl.Name
    If Left(tblName, 4) = "MSys" Then 'System Tables
        GoTo nextstep
    Else
        j = j + 1
On Error Resume Next
        DoCmd.TransferSpreadsheet acExport, _
        acSpreadsheetTypeExcel12Xml, tblName, xlsPath, True
        If Err > 0 Then
            Err.Clear
          debug.print tblName
            j = j - 1
            Resume nextstep
        End If
End If
nextstep:
Next

On Error GoTo Export2Excel_Err

   MsgBox j & " Table(s) Exported to File:" & vbCr & xlsPath, , "Export2Excel()"
   
Set wrkBook = Nothing
Set db = Nothing

Export2Excel_Exit:
Exit Sub

Export2Excel_Err:
MsgBox Err & " : " & Err.Description, , "Export2Excel()"
Resume Export2Excel_Exit
End Sub

Caution: You may compare the worksheet's Maximum Rows available (press End-Key then Down-Arrow Key) in your version of Excel Worksheet to the Access Table with the maximum number of records. If any of the tables have more than the Excel worksheet Rows, then there are chances that the extra records may overflow into a second Worksheet or may get lost in the process.  The above code is not tested for this and use it at your own risk.

Before going through the Code you may attach the Microsoft Excel Object xx.0 Library File to your Access Project, before attempting to compile the above VBA Code.

  1. Open the VBA Editing Window (Alt+F11).

  2. Select References from Tools Menu

  3. Look for Microsoft Excel 16.0 Object Library file in the list.

  4. Put a check mark, on the left side of the file, to select it.

  5. Click OK to close the Object Library files list.

The VBA Code Review.

At the beginning of the Code, the required Variables are declared. 

The xlsFileLoc variable is initialized with the Database Path, and we will be creating a new Workbook, in the current version of Excel you have, in this location to save the Access Tables.

The Workbook name will be AllTables.xlsx, if you would like to give a different name then change it.

The xlsPath Variable is initialized with the Workbook Path and filename.

In the next three steps, we create a new Excel Workbook with the name AllTables.xlsx, save it in the specified location, and close the file. If the file already exists there, then a warning message is displayed. You may either choose to overwrite the existing file or Cancel the export procedure and retain the existing Excel Workbook contents. 

NB: But, the Excel file should not be kept open while exporting the Access Tables. If it is kept open then the export operation will fail. Check the following TransferSpreadsheet Command:

DoCmd.TransferSpreadsheet acExport, _
     acSpreadsheetTypeExcel12Xml, TblName, xlsPath, True

The parameter xlsPath value is where we give a specific Excel Workbook File reference to save the output data. If the Workbook File already exists, then the output will be written into a separate Worksheet in that file.  If you omit this parameter, then it creates a target Work Sheet File based on the second parameter acSpreadsheetTypeExcel12Xml selection, one out of several options available to select from.

Creating a Workbook in the current version of Excel and giving it as the Target Workbook for the output will save all the Tables in separate Worksheets, in the same Workbook, rather than creating every table output creating in a separate Workbook. Besides that, the output data will be formatted with the current Excel version default Office theme.

Note: The Table Export option normally creates an Excel 2003 file automatically, based on one of the export options acSpreadsheetTypeExcel3 - 9 selected and the output data formatting may not be as pleasing as the current version of Excel that you have.  This topic was discussed in detail in an earlier post with the Title: MS Access And Transfer Spreadsheet Command and you may go through it for a better understanding of this procedure, different versions of options available and their output formats, and other important points to note.

In the next step, the Current Database object is assigned to the Object Variable db. The Variable j is used to take a count of Tables, exported into the Excel Workbook.

We can get all the Table names from the TableDefs collection of our Database Object and can pass these names to the Docmd.TransferSpreadSheet Command to transfer the records.

But, besides the user-created Tables, there are some System Tables also (even though they are normally kept hidden) in this collection of TableDefs.  Fortunately, all System Table names start with the letters MSys and we can identify them easily and stop outputting their contents into Excel.

j = 0
For Each Tbl In db.TableDefs
    tblName = Tbl.Name
    If Left(tblName, 4) = "MSys" Then 'System Tables
        GoTo nextstep
    Else
        j = j + 1
On Error Resume Next
        DoCmd.TransferSpreadsheet acExport, _
        acSpreadsheetTypeExcel12Xml, tblName, xlsPath, True
        If Err > 0 Then
            Err.Clear
          Debug.Print tblName
            j = j - 1
            Resume nextstep
        End If
End If
nextstep:
Next

In the above For Each ... Next statement reads each Table definition from the TableDefs collection in the TableDef object Tbl.

The next statement reads the name of the Table from the Name Property into the String Variable tblName.

The next statement checks whether the first four characters of the table name match the text MSys or not. If it does, then it is a System Table and the program skips the remaining part of the Code and goes for taking the next table to validate.

If it is a valid user-created Table then the counter Variable j is incremented by one.  The next Error capture line was added as a precaution to check if anything goes wrong with the TransferSpreadSheet Command.  

Next, the TransferSpreadSheet command is executed and the Records from the Table are transferred into the Excel WorkSheet, if it is a valid table, with the Field Names placed on the first row of the worksheet. 

If the above operation failed due to some unforeseen Error, we ignore that table and go to the next table in line, after the table counter variable is reset to the earlier successful operation count. The name of the Table in Error is dumped into the Debug Window and you may check and take corrective actions on it later. If something happened to a single table, we don't want to stop our operation and expect other tables will output normally.

When finished with the exporting operation, a message is displayed with the count of Tables exported successfully into Excel WorkBook.

You may download the Demo Database attached here and try it right away.

  1. MS Access And Transfer SpreadSheet Command.
  2. Access And Windows API ShowWindow
  3. Database Backup/Restore From Desktop
  4. Get Disk Free Space - Windows API
  5. Access And Windows API ShowWindow
Share:

PRESENTATION: ACCESS USER GROUPS (EUROPE)

Translate

PageRank

Post Feed


Search

Popular Posts

Blog Archive

Powered by Blogger.

Labels

Forms Functions How Tos MS-Access Security Reports msaccess forms Animations msaccess animation Utilities msaccess controls Access and Internet MS-Access Scurity MS-Access and Internet Class Module External Links Queries Array msaccess reports Accesstips WithEvents msaccess tips Downloads Objects Menus and Toolbars Collection Object MsaccessLinks Process Controls Art Work Property msaccess How Tos Combo Boxes Dictionary Object ListView Control Query VBA msaccessQuery Calculation Event Graph Charts ImageList Control List Boxes TreeView Control Command Buttons Controls Data Emails and Alerts Form Custom Functions Custom Wizards DOS Commands Data Type Key Object Reference ms-access functions msaccess functions msaccess graphs msaccess reporttricks Command Button Report msaccess menus msaccessprocess security advanced Access Security Add Auto-Number Field Type Form Instances ImageList Item Macros Menus Nodes RaiseEvent Recordset Top Values Variables Wrapper Classes msaccess email progressmeter Access2007 Copy Excel Export Expression Fields Join Methods Microsoft Numbering System Records Security Split SubForm Table Tables Time Difference Utility WScript Workgroup database function msaccess wizards tutorial Access Emails and Alerts Access Fields Access How Tos Access Mail Merge Access2003 Accounting Year Action Animation Attachment Binary Numbers Bookmarks Budgeting ChDir Color Palette Common Controls Conditional Formatting Data Filtering Database Records Defining Pages Desktop Shortcuts Diagram Disk Dynamic Lookup Error Handler External Filter Formatting Groups Hexadecimal Numbers Import Labels List Logo Macro Mail Merge Main Form Memo Message Box Monitoring Octal Numbers Operating System Paste Primary-Key Product Rank Reading Remove Rich Text Sequence SetFocus Summary Tab-Page Union Query User Users Water-Mark Word automatically commands hyperlinks iSeries Date iif ms-access msaccess msaccess alerts pdf files reference restore switch text toolbar updating upload vba code