Sei sulla pagina 1di 8

01/07/2019 How to Export Access Data to Excel using VBA

Export Access Data to Excel


How to use VBA to export to Excel workbooks data from Access query datasheets and to format the worksheets once the data have arrived.

Last updated on 2019-03-26 by David Wallis.

Preface
For many of the databases I develop I include an export-to-Excel capability. This is for clients who want the means of dumping data so that they can do their own thing without risk to the primary data.

Quite often an export in itself is all that’s required, instead of a carefully created Access report included in the database. Also, on occasions, the export serves as a useful check that the assembled records contain exactly what the client needs, prior to creation of a full-blown Access
report.

This article describes a VBA procedure for dumping data from Access into Excel, exploiting the DoCmd.TransferSpreadsheet method to take you beyond the explanation of the workings of this method that you read in many websites.

Initial Considerations

Compounded from client requirements over the years, I've identified these are the main features of an export-to-Excel capability:

Automated export of data sets from queries


Export directed to workbooks in folders of the client’s choice
Automated formatting of worksheets on completion of an export

The possibility of users creating their own queries.

All DMW databases supplied to clients are split — FE (Front End) and BE (Back End). FEs contain queries, forms, reports, macros and modules, and, as appropriate, a table or two, as I'll explain below. BEs contain tables only.

From the viewpoint of a developer, these are my considerations:

Users not to be allowed to modify the structure of the BE


Users not to be allowed to alter the FE
Provision for users to create their own queries
Provision for incorporation of users’ own queries into FE
Give suitable control of the process to the client’s IT.

Were users to be allowed to tinker, it would be an impractical and time-consuming task for me providing upgrades and on-gong support to the client. The client would not be happy with the bill.

VBA TransferSpreadsheet Method


The procedure dmwExport uses the bare bones of the TransferSpreadsheet method to export the contents of a table, or of a query datasheet, as a named Excel file to a named folder:

https://www.consultdmw.com/export-access-data-to-excel.html 1/8
01/07/2019 How to Export Access Data to Excel using VBA

Sub dmwExport
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DoCmd.TransferSpreadsheet _
TransferType:=acExport, _
SpreadsheetType:=acSpreadsheetTypeExcel12Xml, _
TableName:=query$ ,_
FileName:=path$, _
HasFieldNames:=True
End Sub

dmwExport("qsResults", "S:\Reports\Results.XLSX"), for example, exports the contents of the query qsResults to the folder S:\Reports\ as an Excel file named Results.XLSX.

Opening the Exported Workbook


dmwExport creates the workbook and saves it, but it doesn't display the completed workbook. Experience suggests that most users want to see the results of the export as soon as it's complete.

Sub dmwExport(query$, path$)


'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Dim xlApp As Object, wkbk As Object
DoCmd.TransferSpreadsheet _
TransferType:=acExport, _
SpreadsheetType:=acSpreadsheetTypeExcel12Xml, _
TableName:=query$, _
FileName:=path$, _
HasFieldNames:=True
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
Set wkbk = .Workbooks.Open(path$)
End With
End Sub

Error Handling
At this point we will include error handling and make sure that the procedure releases any connection with Excel once it has presented the workbook:

Sub dmwExport(query$, path$)


'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
On Error Goto errHandler
Dim xlApp As Object, wkbk As Object
Dim msg$

DoCmd.TransferSpreadsheet _
TransferType:=acExport, _
SpreadsheetType:=acSpreadsheetTypeExcel12Xml, _
TableName:=query$, _
FileName:=path$, _
HasFieldNames:=True
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
Set wkbk = .Workbooks.Open(path$)
End With

procDone:
Set wkbk = Nothing
Set xlApp = Nothing
Exit Sub
errHandler:
msg$ = Err.Description

https://www.consultdmw.com/export-access-data-to-excel.html 2/8
01/07/2019 How to Export Access Data to Excel using VBA

MsgBox msg$, vbExclamation, "Unanticipated Error"


Resume procDone
End Sub

Path and Workbook Naming


You need to take care when supplying values to the path$ argument of dmwExport(query$, path$). Consider these values:

"S:\Reports\Results.XLSX" This works satisfactorily — the Workbook named Results.XLSX is directed to the S:\Reports\ folder.

"S:\Reports\Results" This works satisfactorily too — the procedure attaches the .XLSX extension to the workbook's name so that Results.XLSX is directed to the S:\Reports\ folder.

"S:\Reports\Results\" Here the problem arises that the final \ causes the procedure to treat S:\Reports\Results\ as a folder, without specifying any workbook at all, with resulting error conditions, eg —

If there’s call for it (let me know), I shall add some code to contend with the issue. The full-blown export program described below incudes such code.

Providing for Folder Changes


In my experience, clients like to be able to determine for themselves to which folder the export process directs the workbooks it creates. Also, they want to be able to change that folder without needing to get me to tweak any code. This is a particular requirement when a client’s IT want
the freedom to change locations for files on a network and re-map drives.

Over the years, I’ve tried a number of ways of providing for this, currently settling with a method that uses an addition to the two main FE and BE files. This third file I name KEY.ini, which is a simple text file, the content of which is this:

Important
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This file to be placed in same folder as USER file
Edit ExportPath to correspond to your folder structure
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DEFAULT]
ExportPath = "S:\Reports\"

Now we need to accommodate KEY.ini into the export process. The process must pick out the export path from KEY.ini.

In tune with good practice we are going to structure our programming by separating our code into a number of sub-routines. Each of these will perform a distinct operation, one of which will be the picking from KEY.ini.

From here on in dmwExport will become one of the sub-routines the running sequences of which will be determined by an overall controlling procedure.

The Controlling Procedure


This is the sequence of sub-routines that the controlling procedure, or program, named dmwExportToXL, will call:

dmwGetPath This VBA-function sub-routine will look for KEY.ini and get the export path from it. If dmwGetPath cannot locate KEY.ini, or is unable the find the information about the export path, then it will return an error message to dmwExportToXL.

dmwCheckPath This VBA-function sub-routine will seek to confirm the existence of the folder to which dumps are to be directed. If dmwCheckPath cannot locate that folder it will it report is as missing to dmwExportToXL.

dmwExport This will complete the export program passing data from Access and into Excel, the opening Excel to display the data, and the formatting of the worksheet.

This is the skeleton of the dmwExportToXL program:

Sub dmwExportToXL()
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Dim msg$, bln As Boolean
msg$ = dmwGetPathFromKEY()
bln = dmwCheckPath()
Call dmwExport()
End Function

https://www.consultdmw.com/export-access-data-to-excel.html 3/8
01/07/2019 How to Export Access Data to Excel using VBA

Get Path from KEY File Sub-Routine


The job of the sub-routine dmwGetPathFromKEY is to retrieve the path of the back-end DATA file from KEY.ini:

Function dmwGetPathFromKEY(pathINI$, element$) As String


'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
On Error GoTo errHandler
Dim i&, lenElement&
Dim fstChar34%, lstChar34%
Dim lineINI$, path$

If Len(Dir(pathINI$)) > 0 And Len(element$) > 0 Then


lenElement& = Len(element$)
i& = FreeFile()
Open pathINI$ For Input As #i&

Do While Not EOF(i&)


Line Input #i&, lineINI$
If Left(lineINI$, lenElement&) = element$ Then
path$ = Mid(lineINI$, lenElement& + 1)
Exit Do
End If
Loop
Close #i&

fstChar34% = InStr(path$, Chr(34)) + 1


lstChar34% = InStrRev(path$, Chr(34))
path$ = Mid(path$, fstChar34%, lstChar34% - fstChar34%)
Else
path$ = "Error"
End If

procDone:
dmwGetPathFromKEY = path$
Exit Function
errHandler:
path$ = "Error"
Resume procDone
End Function

If it's unable to return the whereabouts of DATA, then dmwGetPathFromKEY warnings from which dmwStartUp composes messages to the user.

Check Path Sub-Routine


The job of the second sub-routine, dmwCheckPath, in the export program is to confirm that the folder specified in KEY.ini actually exists:

Function dmwCheckPath(path$) As String


'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
On Error GoTo errHandler
Dim msg$

If Dir(path$, vbDirectory) = "." Then


msg$ = vbNullString
Else
msg$ = _
"No folder matches entry in KEY file"
End If

procDone:
dmwCheckPath = msg$
Exit Function
errHandler:

https://www.consultdmw.com/export-access-data-to-excel.html 4/8
01/07/2019 How to Export Access Data to Excel using VBA

msg$ = Err.Description
Resume procDone
End Function

dmwCheckPath returns a null string if the folder is in place, or a message if that folder is missing or that the program cannot find it at the anticipated location.

Export to Excel Sub-Routine


The third and final subroutine in the program is dmwExport. But unlike the version at the top of this page, this version of dmwExport contains lines of code aimed at smartening up the contents of the worksheet created by the export.

The smartening up that my clients most like to see are these:

Formatting of column headings

Application of a currency format to columns, where appropriate


Application of a date format to columns, where appropriate

Adjustment of columns widths to suit content


Appropriate naming of the worksheet's tab.

Hence a revised dmwExport, now fashioned as a function procedure:

Function dmwExport( _
query$, path$, _
fileName$, wksName$, _
colsCurrency$, colsDate$ _
) As String
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
On Error GoTo errHandler
Dim xlApp As Object, wkbk As Object, wks As Object
Dim file$
Dim formatCur$, formatDate$, intColor&
Dim arrayCols() As String, col$, n%, i%, w!
Dim cell As Range
Dim msg$

' Worksheet formats


formatCur$ = "£#,##0.00"
formatDate$ = "yyyy-mm-dd"
intColor& = RGB(100, 200, 200)

' Create workbook


file$ = path$ & fileName$
DoCmd.TransferSpreadsheet _
TransferType:=acExport, _
SpreadsheetType:=acSpreadsheetTypeExcel12Xml, _
TableName:=query$, _
FileName:=file$, _
HasFieldNames:=True

' Open workbook


Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
Set wkbk = .Workbooks.Open(file$)
End With

' Format worksheet


Set wks = wkbk.worksheets(1)
With wks
.Name = wksName$

' Currency columns


arrayCols = Split(colsCurrency$, ",")
For i = LBound(arrayCols) To UBound(arrayCols)
https://www.consultdmw.com/export-access-data-to-excel.html 5/8
01/07/2019 How to Export Access Data to Excel using VBA

With .Columns(arrayCols(i))
.NumberFormat = formatCur$
End With
Next i

' Date columns


arrayCols = Split(colsDate$, ",")
For i = LBound(arrayCols) To UBound(arrayCols)
With .Columns(arrayCols(i))
.NumberFormat = formatDate$
End With
Next i

' Filters
With .Range("A1")
.Select
.autofilter
End With

' Column width adjustments


With .Cells
.Select
.EntireColumn.AutoFit
End With
n% = .Cells(1, 1).End(xlToRight).Column
For i% = 1 To n%
With .Cells(1, i%)
w! = .EntireColumn.ColumnWidth
.EntireColumn.ColumnWidth = w! + 4
.HorizontalAlignment = xlCenter
.Interior.Color = intColor&
.Font.Bold = True
End With
Next i%
End With

With xlApp.ActiveWindow
.SplitColumn = 0
.SplitRow = 1
.FreezePanes = True
End With
msg$ = vbNullString

procDone:
Set wks = Nothing
Set wkbk = Nothing
Set xlApp = Nothing
dmwExport = msg$
Exit Function
errHandler:
msg$ = _
Err.Number & ": " & Err.Description
Resume procDone
End Function

Export to Excel Program Procedure


This is the controlling procedure that pulls together the sub-procedures to perform the export to Excel:

Function dmwExportToXL(query$, _
fileName$, wksName$, _
colsCurrency$, colsDate$)
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
https://www.consultdmw.com/export-access-data-to-excel.html 6/8
01/07/2019 How to Export Access Data to Excel using VBA

On Error GoTo errHandler


Dim bln As Boolean
Dim path$
Dim msg$

path$ = Left(CurrentProject.FullName, _
InStrRev(CurrentProject.FullName, "\"))
path$ = path$ & "KEY.ini"

path$ = dmwGetPathFromKEY(path$, "ExportPath")


Select Case path$
Case "Error"
msg$ = "Unanticipated error locating KEY"
bln = False
Case Else
bln = True
End Select

If bln Then msg$ = dmwCheckPath(path$)


If msg$ = vbNullString Then
msg$ = dmwExport( _
query$, path$, _
fileName$, wksName$, _
colsCurrency$, colsDate$)
Else
msg$ = _
"Folder for exports cannot be located. " & msg$
End If

procDone:
If msg$ <> vbNullString Then
MsgBox msg$, vbExclamation, "Excel Export"
End If
Exit Function
errHandler:
msg$ = Err.Number & ": " & Err.Description
Resume procDone
End Function

This is how you might provide values for the arguments of dmwExportToXL:

query$ as “qsExportSales” — your database query

fileName$ as “Hello” — the workbook file's name.

wksName$ as “World” — the worksheet’s name

colsCurrency$ as “F:F” — Column F currency format

colsDate$ as “C:C,D:D” — Columns C and D date format.

Each argument value must be enclosed in the quotation marks as shown above.

Download and Donation


Download
If you’re going to make use of T  in any of your professional or commercial work, then please consider making a payment in recognition of the time spent publishing this website.

To make a contribution by PayPal in GBP (£ sterling) —

To make a contribution by PayPal in USD ($ US) —

https://www.consultdmw.com/export-access-data-to-excel.html 7/8
01/07/2019 How to Export Access Data to Excel using VBA

To say how much you want to pay and to receive


a tax invoice for a GBP (£ sterling) contribution —

Invoice

Thanks, in anticipation.

Front End Table Linking Failures


On a couple of occasions getting a new database up-and-running, users reported this error and the database failing to open:

The cause of the error was lack of permissions assigned to all the users. To avoid the error, make sure that each user is given full admission to the database BE, and to the folder and drives in which it is located.

HOME DATABASES SPREADSHEETS TEMPLATES CONSULTANCY ☰ TRAINING CONTACT

“And now for something completely different.”

Monty Python

☰A T

https://www.consultdmw.com/export-access-data-to-excel.html 8/8

Potrebbero piacerti anche