VBA TUTORIAL
VBA CODE GENERATOR
VBA CODE EXAMPLES
VBA GUIDES
Sign in
Return to VBA Code Examples
Access VBA – Import / Export Excel – Query, Report,
Table, and Forms
This tutorial will cover the ways to import data from Excel into an Access Table and ways to export
Access objects (Queries, Reports, Tables, or Forms) to Excel.
Import Excel File Into Access
To import an Excel file to Access, use the acImport option of [Link] :
[Link] acImport, acSpreadsheetTypeExcel12, "Table1",
"C:\Temp\[Link]", True
Or you can use [Link] to import a CSV file:
[Link] acLinkDelim, , "Table1", "C:\Temp\[Link]", True
Import Excel to Access Function
This function can be used to import an Excel file or CSV file into an Access Table:
Public Function ImportFile(Filename As String, HasFieldNames As Boolean, TableName As
String) As Boolean
' Example usage: call ImportFile ("Select an Excel File", "Excel Files", "*.xlsx",
"C:\" , True,True, "ExcelImportTest", True, True,false,True)
On Error GoTo err_handler
If (Right(Filename, 3) = "xls") Or ((Right(Filename, 4) = "xlsx")) Then
[Link] acImport, acSpreadsheetTypeExcel12,
TableName, Filename, blnHasFieldNames
End If
If (Right(Filename, 3) = "csv") Then
[Link] acLinkDelim, , TableName, Filename, True
End If
Exit_Thing:
'Clean up
'Check if our linked in Excel table already exists... and delete it if so
If ObjectExists("Table", TableName) = True Then DropTable (TableName)
Set colWorksheets = Nothing
Exit Function
err_handler:
If ([Link] = 3086 Or [Link] = 3274 Or [Link] = 3073) And errCount < 3
Then
errCount = errCount + 1
ElseIf [Link] = 3127 Then
MsgBox "The fields in all the tabs are the same. Please make sure that each
sheet has the exact column names if you wish to import mulitple", vbCritical,
"MultiSheets not identical"
ImportFile = False
GoTo Exit_Thing
Else
MsgBox [Link] & " - " & [Link]
ImportFile = False
GoTo Exit_Thing
Resume
End If
End Function
You can call the function like this:
Private Sub ImportFile_Example()
Call VBA_Access_ImportExport.ImportFile("C:\Temp\[Link]", True,
"Imported_Table_1")
End Sub
VBA - AutoMacro - Getting Started
AUTOMACRO - VBA CODE GENERATOR
Learn More
Access VBA Export to New Excel File
To export an Access object to a new Excel file, use the [Link] method or
the [Link] method:
Export Query to Excel
This line of VBA code will export a Query to Excel using [Link]:
[Link] acOutputQuery, "Query1", acFormatXLSX, "c:\temp\[Link]"
Or you can use the [Link] method instead:
[Link] acExport, acSpreadsheetTypeExcel8, "Query1",
"c:\temp\[Link]", True
Note: This code exports to XLSX format. Instead you can update the arguments to export to a CSV
or XLS file format instead (ex. acFormatXLSX to acFormatXLS).
Export Report to Excel
This line of code will export a Report to Excel using [Link]:
[Link] acOutputReport, "Report1", acFormatXLSX, "c:\temp\[Link]"
Or you can use the [Link] method instead:
[Link] acExport, acSpreadsheetTypeExcel8, "Report1",
"c:\temp\[Link]", True
Export Table to Excel
This line of code will export a Table to Excel using [Link]:
[Link] acOutputTable, "Table1", acFormatXLSX, "c:\temp\[Link]"
Or you can use the [Link] method instead:
[Link] acExport, acSpreadsheetTypeExcel8, "Table1",
"c:\temp\[Link]", True
Export Form to Excel
This line of code will export a Form to Excel using [Link]:
[Link] acOutputForm, "Form1", acFormatXLSX, "c:\temp\[Link]"
Or you can use the [Link] method instead:
[Link] acExport, acSpreadsheetTypeExcel8, "Form1",
"c:\temp\[Link]", True
Export to Excel Functions
These one line commands work great to export to a new Excel file. However, they will not be able to
export into an existing workbook. In the section below we introduce functions that allow you to
append your export to an existing Excel file.
Below that, we’ve included some additional functions to export to new Excel files, including error
handling and more.
Export to Existing Excel File
The above code examples work great to export Access objects to a new Excel file. However, they
will not be able to export into an existing workbook.
To export Access objects to an existing Excel workbook we’ve created the following function:
Public Function AppendToExcel(strObjectType As String, strObjectName As String,
strSheetName As String, strFileName As String)
Dim rst As [Link]
Dim ApXL As [Link]
Dim xlWBk As [Link]
Dim xlWSh As [Link]
Dim intCount As Integer
Const xlToRight As Long = -4161
Const xlCenter As Long = -4108
Const xlBottom As Long = -4107
Const xlContinuous As Long = 1
Select Case strObjectType
Case "Table", "Query"
Set rst = [Link](strObjectName, dbOpenDynaset, dbSeeChanges)
Case "Form"
Set rst = Forms(strObjectName).RecordsetClone
Case "Report"
Set rst = [Link](Reports(strObjectName).RecordSource,
dbOpenDynaset, dbSeeChanges)
End Select
If [Link] = 0 Then
MsgBox "No records to be exported.", vbInformation, GetDBTitle
Else
On Error Resume Next
Set ApXL = GetObject(, "[Link]")
If [Link] <> 0 Then
Set ApXL = CreateObject("[Link]")
End If
[Link]
[Link] = False
Set xlWBk = [Link](strFileName)
Set xlWSh = [Link]
[Link] = Left(strSheetName, 31)
[Link]("A1").Select
Do Until intCount = [Link]
[Link] = [Link](intCount).Name
[Link](0, 1).Select
intCount = intCount + 1
Loop
[Link]
[Link]("A2").CopyFromRecordset rst
With ApXL
.Range("A1").Select
.Range(.Selection, .[Link](xlToRight)).Select
.[Link] = xlSolid
.[Link] = xlAutomatic
.[Link] = -0.25
.[Link] = 0
.[Link] = xlNone
.[Link]
.[Link]
.[Link]
.Range("B2").Select
.[Link] = True
.[Link]
.[Link] = False
.[Link]
[Link]("A1").Select
.Visible = True
End With
'[Link] True
'Set xlWB = Nothing
'[Link]
'Set ApXL = Nothing
End If
End Function
You can use the function like this:
Private Sub AppendToExcel_Example()
Call VBA_Access_ImportExport.ExportToExcel("Table", "Table1", "VBASheet",
"C:\Temp\[Link]")
End Sub
Notice you are asked to define:
What to Output? Table, Report, Query, or Form
Object Name
Output Sheet Name
Output File Path and Name.
Export SQL Query to Excel
Instead you can export an SQL query to Excel using a similar function:
Public Function AppendToExcelSQLStatemet(strsql As String, strSheetName As String,
strFileName As String)
Dim strQueryName As String
Dim ApXL As [Link]
Dim xlWBk As [Link]
Dim xlWSh As [Link]
Dim intCount As Integer
Const xlCenter As Long = -4108
Const xlBottom As Long = -4107
Const xlVAlignCenter = -4108
Const xlContinuous As Long = 1
Dim qdf As [Link]
Dim rst As [Link]
strQueryName = "tmpQueryToExportToExcel"
If ObjectExists("Query", strQueryName) Then
[Link] strQueryName
End If
Set qdf = [Link](strQueryName, strsql)
Set rst = [Link](strQueryName, dbOpenDynaset)
If [Link] = 0 Then
MsgBox "No records to be exported.", vbInformation, GetDBTitle
Else
On Error Resume Next
Set ApXL = GetObject(, "[Link]")
If [Link] <> 0 Then
Set ApXL = CreateObject("[Link]")
End If
[Link]
[Link] = False
Set xlWBk = [Link](strFileName)
Set xlWSh = [Link]
[Link] = Left(strSheetName, 31)
[Link]("A1").Select
Do Until intCount = [Link]
[Link] = [Link](intCount).Name
[Link](0, 1).Select
intCount = intCount + 1
Loop
[Link]
[Link]("A2").CopyFromRecordset rst
With ApXL
.Range("A1").Select
.Range(.Selection, .[Link](xlToRight)).Select
.[Link] = xlSolid
.[Link] = xlAutomatic
.[Link] = -0.25
.[Link] = 0
.[Link] = xlNone
.[Link]
.[Link]
.[Link]
.Range("B2").Select
.[Link] = True
.[Link]
.[Link] = False
.[Link]
[Link]("A1").Select
.Visible = True
End With
'[Link] True
'Set xlWB = Nothing
'[Link]
'Set ApXL = Nothing
End If
End Function
Called like this:
Private Sub AppendToExcelSQLStatemet_Example()
Call VBA_Access_ImportExport.ExportToExcel("SELECT * FROM Table1", "VBASheet",
"C:\Temp\[Link]")
End Sub
Where you are asked to input:
SQL Query
Output Sheet Name
Output File Path and Name.
Function to Export to New Excel File
These functions allow you to export Access objects to a new Excel workbook. You might find them
more useful than the simple single lines at the top of the document.
Public Function ExportToExcel(strObjectType As String, strObjectName As String,
Optional strSheetName As String, Optional strFileName As String)
Dim rst As [Link]
Dim ApXL As Object
Dim xlWBk As Object
Dim xlWSh As Object
Dim intCount As Integer
Const xlToRight As Long = -4161
Const xlCenter As Long = -4108
Const xlBottom As Long = -4107
Const xlContinuous As Long = 1
On Error GoTo ExportToExcel_Err
[Link] True
Select Case strObjectType
Case "Table", "Query"
Set rst = [Link](strObjectName, dbOpenDynaset, dbSeeChanges)
Case "Form"
Set rst = Forms(strObjectName).RecordsetClone
Case "Report"
Set rst = [Link](Reports(strObjectName).RecordSource,
dbOpenDynaset, dbSeeChanges)
End Select
If [Link] = 0 Then
MsgBox "No records to be exported.", vbInformation, GetDBTitle
[Link] False
Else
On Error Resume Next
Set ApXL = GetObject(, "[Link]")
If [Link] <> 0 Then
Set ApXL = CreateObject("[Link]")
End If
[Link]
On Error GoTo ExportToExcel_Err
Set xlWBk = [Link]
[Link] = False
Set xlWSh = [Link]("Sheet1")
If Len(strSheetName) > 0 Then
[Link] = Left(strSheetName, 31)
End If
[Link]("A1").Select
Do Until intCount = [Link]
[Link] = [Link](intCount).Name
[Link](0, 1).Select
intCount = intCount + 1
Loop
[Link]
[Link]("A2").CopyFromRecordset rst
With ApXL
.Range("A1").Select
.Range(.Selection, .[Link](xlToRight)).Select
.[Link] = xlSolid
.[Link] = xlAutomatic
.[Link] = -0.25
.[Link] = 0
.[Link] = xlNone
.[Link]
.[Link]
.[Link]
.Range("B2").Select
.[Link] = True
.[Link]
.[Link] = False
.[Link]
[Link]("A1").Select
.Visible = True
End With
retry:
If FileExists(strFileName) Then
Kill strFileName
End If
If strFileName <> "" Then
[Link] strFileName, FileFormat:=56
End If
[Link]
Set rst = Nothing
[Link] False
End If
ExportToExcel_Exit:
[Link] False
Exit Function
ExportToExcel_Err:
[Link] True
MsgBox [Link], vbExclamation, [Link]
[Link] False
Resume ExportToExcel_Exit
End Function
The function can be called like this:
Private Sub ExportToExcel_Example()
Call VBA_Access_ImportExport.ExportToExcel("Table", "Table1", "VBASheet")
End Sub
817 Reviews
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam
add-in.
(No installation required!)
Free Download
Return to VBA Code Examples Menu
Excel and VBA Consulting
Get a Free Consultation
VBA CODE GENERATOR
VBA TUTORIAL
VBA CODE EXAMPLES FOR EXCEL
EXCEL BOOT CAMP
FORMULAS TUTORIAL
EXCEL FORMULAS EXAMPLES LIST
FUNCTIONS LIST
SHORTCUT COACH
SHORTCUT TUTORIAL
SHORTCUTS LIST
Register for FREE and get:
VBA EXAMPLES ADD-IN
VBA CHEATSHEETS PDFS
VBA TUTORIAL PDFS
Register for free
© 2021 Spreadsheet Boot Camp LLC. All Rights Reserved.
PRIVACY
DISCLAIMER
ABOUT
VBA (Macros)
Code Examples Add-in
Free Download
Download our VBA Macro Code Examples Add-in Download 100% Free