Reputation: 31
I need some help with export multiple queries into one excel Workbook, but, multiple Worksheet? using the criteria from a table in MS Access VBA
ATTACHED IS DB for Reference.
Based on the Unique values in the column "System" in table "Tbl_Final" (SQL query below), I need to create INDIVIDUAL excel files and export it to folder. Example: SELECT TBL_FINAL.System, TBL_FINAL.[User ID], TBL_FINAL.[User Type], TBL_FINAL.Status, TBL_FINAL.[Job Position] FROM TBL_FINAL WHERE (((TBL_FINAL.System)="OS/400"));
SELECT TBL_FINAL.System, TBL_FINAL.[User ID], TBL_FINAL.[User Type], TBL_FINAL.Status, TBL_FINAL.[Job Position]
FROM TBL_FINAL
WHERE (((TBL_FINAL.System)="Tab"));
After googling, i managed to find a code which matches the criterion. But encountring some hurdles :(
Request for some help !!
Option Compare Database
Private Sub Command1_Click()
Dim strSQL As String
Dim dbs As Database
Dim qdf As QueryDef
strQry = "REPORT_QUERY"
Set dbs = CurrentDb
Set qdf = dbs.CreateQueryDef(strQry)
strSQL = "SELECT System, [User ID], [User Type], [Status] FROM TBL_FINAL WHERE System = 'OS/400'"
qdf.SQL = strSQL
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel11, _
strQry, "C:\Program Files\Export\GENERAL_EXPORT.xls", True, _
"Sheet1"
strSQL = "SELECT System, [User ID], [User Type], [Status] FROM TBL_FINAL WHERE System = 'MySys'"
qdf.SQL = strSQL
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel11, _
strQry, "C:\Program Files\Export\GENERAL_EXPORT.xls", True, _
"Sheet2"
DoCmd.DeleteObject acQuery, strQry
End Sub
Upvotes: 3
Views: 37854
Reputation: 123654
The following VBA code works for me, creating a new Excel workbook (.xlsx
file) containing multiple worksheets (mySheet1
and mySheet2
):
Option Compare Database
Option Explicit
Sub ExportToXlsx()
Dim cdb As DAO.Database, qdf As DAO.QueryDef
Set cdb = CurrentDb
Const xlsxPath = "C:\Users\Gord\Desktop\foo.xlsx"
' create .xlsx file if it doesn't already exist, and add the first worksheet
Set qdf = cdb.CreateQueryDef("mySheet1", _
"SELECT * FROM Clients WHERE ID Between 1 And 5")
Set qdf = Nothing
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "mySheet1", xlsxPath, True
DoCmd.DeleteObject acQuery, "mySheet1"
' file exists now, so this will add a second worksheet to the file
Set qdf = cdb.CreateQueryDef("mySheet2", _
"SELECT * FROM Clients WHERE ID Between 6 And 10")
Set qdf = Nothing
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "mySheet2", xlsxPath, True
DoCmd.DeleteObject acQuery, "mySheet2"
Set cdb = Nothing
End Sub
Note that the name of the worksheet is taken from the name of the query (or table) being exported. If a worksheet with that name does not exist in the Excel file then it will be added.
Upvotes: 4