Examples for Exporting Access table or query to EXCEL Workbook Files Part 6

Write Data From a Recordset into an EXCEL Worksheet using EXCEL’s CopyFromRecordset (VBA)

Code to open a recordset for the data that are to be written into a worksheet in an EXCEL file (for this example, the EXCEL file does not already exist), and then to use EXCEL’s CopyFromRecordset method to copy the data from the recordset into the first worksheet in that EXCEL file, with each record being written into a separate row in the worksheet. The code allows for a header row to be created in the worksheet if this is desired. This code example uses “late binding” for the EXCEL automation.

Dim lngColumn As Long
Dim xlx As Object, xlw As Object, xls As Object, xlc As Object
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim strPathFileName As String, strWorksheetName As String
Dim strRecordsetDataSource As String
Dim blnEXCEL As Boolean, blnHeaderRow As Boolean

blnEXCEL = False

‘ Replace C:\Filename.xls with the actual path and filename
‘ that will be used to save the new EXCEL file into which you
‘ will write the data
strPathFileName = "C:\Filename.xls"

‘ Replace QueryOrTableName with the real name of the table or query
‘ whose data are to be written into the worksheet
strRecordsetDataSource = "QueryOrTableName"

‘ Replace True with False if you do not want the first row of
‘ the worksheet to be a header row (the names of the fields
‘ from the recordset)
blnHeaderRow = True

‘ Establish an EXCEL application object
On Error Resume Next
Set xlx = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
Set xlx = CreateObject("Excel.Application")
blnEXCEL = True
End If
On Error GoTo 0

‘ Change True to False if you do not want the workbook to be
‘ visible when the code is running
xlx.Visible = True

‘ Create a new EXCEL workbook
Set xlw = xlx.Workbooks.Add

‘ Rename the first worksheet in the EXCEL file to be the first 31
‘ characters of the string in the strRecordsetDataSource variable
Set xls = xlw.Worksheets(1)
xls.Name = Trim(Left(strRecordsetDataSource, 31))

‘ Replace A1 with the cell reference of the first cell into which the
‘ headers will be written (blnHeaderRow = True), or into which the data
‘ values will be written (blnHeaderRow = False)
Set xlc = xls.Range("A1")

Set dbs = CurrentDb()

Set rst = dbs.OpenRecordset(strRecordsetDataSource, dbOpenDynaset, dbReadOnly)

If rst.EOF = False And rst.BOF = False Then
‘ Write the header row to worksheet
If blnHeaderRow = True Then
For lngColumn = 0 To rst.Fields.Count – 1
xlc.Offset(0, lngColumn).Value = rst.Fields(lngColumn).Name
Next lngColumn
Set xlc = xlc.Offset(1,0)
End If

‘ copy the recordset’s data to worksheet
xlc.CopyFromRecordset rst
End If

Set rst = Nothing
Set dbs = Nothing

‘ Save and close the EXCEL file, and clean up the EXCEL objects
Set xlc = Nothing
Set xls = Nothing
xlw.SaveAs strPathFileName
xlw.Close False
Set xlw = Nothing
If blnEXCEL = True Then xlx.Quit
Set xlx = Nothing


Leave a Reply