I'm trying something quite basic I assume but it's not working. I want to append the contents of an access table to an excel file or create the excel file if it does not exist. So far I either get errors or the excel file is overwritten instead of the data being appended.
This is my full code:
This is the part of the code where things go wrong:
It tries to create a new file, so I'm either using range parameter wrong or the command is only used for creating files not appending data to files.
This is my full code:
Code:
Sub ExportArchiveToExcel()
Dim archiveFileName As String
Dim archiveFilePath As String
Dim recordCount As Long
Dim yearPart As String
Dim excelApp As Object
Dim excelWorkbook As Object
Dim excelWorksheet As Object
' ---- Export to Excel ----
' Create the archive file name
yearPart = Format(Now, "yyyy")
archiveFileName = "DayShelfAdjLog_" & yearPart & ".xlsx"
' Determine the archive file path (in the same folder as the db)
archiveFilePath = CurrentProject.Path & "\" & archiveFileName
' Count the records in tbl_logs_archive
recordCount = DCount("*", "tbl_logs_archive")
' Nothing to do if there no records
If recordCount > 0 Then
' Check if the archive file already exists
If Len(Dir(archiveFilePath)) = 0 Then
Debug.Print "Archive file missing, creating a new one, condition: " & Len(Dir(archiveFilePath))
' If it doesn't exist, create a new Excel file
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, _
"tbl_logs_archive", archiveFilePath, True
Else
Debug.Print "Found an existing file"
End If
' Open the Excel application
Set excelApp = CreateObject("Excel.Application")
' Open the Excel workbook
Set excelWorkbook = excelApp.Workbooks.Open(archiveFilePath)
' Set active worksheet name
Set excelWorksheet = excelWorkbook.Sheets("tbl_logs_archive")
' Find the last row with data in the worksheet
Dim lastRow As Long
lastRow = excelWorksheet.Cells(excelWorksheet.Rows.Count, "A").End(-4162).Row + 1
' Export data from tbl_logs_archive starting from the next available row
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, _
"tbl_logs_archive", archiveFilePath, True, excelWorksheet.Name & "!A" & lastRow
' Save and close the Excel workbook
excelWorkbook.Save
excelWorkbook.Close
excelApp.Quit
' Release Excel objects
Set excelWorksheet = Nothing
Set excelWorkbook = Nothing
Set excelApp = Nothing
'------------------
Else
' If tbl_logs_archive has no entries, display a message
Debug.Print "No records to export to Excel.", vbInformation
End If
This is the part of the code where things go wrong:
Code:
' Export data from tbl_logs_archive starting from the next available row
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, _
"tbl_logs_archive", archiveFilePath, True, excelWorksheet.Name & "!A" & lastRow
It tries to create a new file, so I'm either using range parameter wrong or the command is only used for creating files not appending data to files.