Hi cantona
Have a look at the following functions :
Function Excel_AddQuery(xl As Object, wb As Excel.Workbook, qry As String)
Dim rs As New ADODB.Recordset
Dim fc As Integer
Dim row As Integer
wb.Sheets.Add
wb.ActiveSheet.Name = qry
rs.Open qry, CurrentProject.Connection, adOpenKeyset, adLockReadOnly
If Not rs.EOF Then
fc = 1
While (fc < rs.Fields.Count)
xl.Cells(1, fc) = rs(fc).Name
fc = fc + 1
Wend
row = 2
While Not rs.EOF
fc = 1
While (fc < rs.Fields.Count)
xl.Cells(row, fc) = rs(fc)
fc = fc + 1
Wend
row = row + 1
rs.MoveNext
Wend
End If
rs.Close
Set rs = Nothing
End Function
Function MyExcelExport(qry As String, qry2 As String, SaveName As String)
Dim wbc As Integer
Dim wb As Excel.Workbook
Dim xl As Object
Set xl = CreateObject("Excel.Application")
xl.visible = True
Set wb = xl.Workbooks.Add
' remove all the sheets from the new book
wbc = wb.Sheets.Count
While (wb.Sheets.Count > 1)
wb.Sheets(1).Delete
Wend
Excel_AddQuery xl, wb, qry
Excel_AddQuery xl, wb, qry2
wb.SaveAs SaveName
wb.Close False
Set wb = Nothing
xl.Quit
Set xl = Nothing
End Function
MyExcelExport expects 3 arguments : query1 , query2 and the name you want to save the excel document as.
Excel_AddQuery is used by MyExcelExport and really you don't need to call it it all.
I have written as a 2 based queries but you can easily adapt it to pass 3 4 or more queries..
MyExcelExport does :
1) Opens Excel
2) Removes all existing sheets
3) For each query it passes to Excel_AddQuery
4) Saves the spreadsheet
5) Closes the spreadsheet
6) Closes excel
Excel_AddQuery
1) Adds a new sheet to excel workbook
2) opens the query recordset
3) Extracts the fieldnames of the query and creates a header row in the sheet from them
4) Loops through the recordset putting each record into the spreadsheet
5) closes the query recordset
hope that made sense..try it..
I used Access 2002 , had to make a reference to Microsoft Excel 10.0 Object Library.. should work with other versions ok..
Hope this helps!
Regards
BuilderSpec