Song Su said:
Access 2003
I have a query called MyRoster. I setup a form and ask user to type in
Employee Number which will be a criterial in my MyRoster query.
I want user to click a command button on my form so the query result will
be exported to Excel and the Excel should open and show. How to do that?
I think I can help you, but it would help me
if you could post back the SQL of your query.
In a general sense, I would imagine you have
a table "tblRoster" with fields
[Employee Number] (type Long)
Field2
Field3
Field4
You would have a combo box on your form
(say "cmboEmpNum") whose source was
SELECT DISTINCT tblRoster.[Employee Number]
FROM tblRoster ORDER BY tblRoster.[Employee Number]
Your user selects an empnum in combobox,
then clicks on a command button (say "cmdOpenXLS")
whose event code might look like:
(***UNTESTED***)
Private Sub cmdOpenXLS_Click()
On Error GoTo Err_cmdOpenXLS_Click
Dim strSQL As String
Dim lngEmpNum As Long
Dim strExcelPath As String
Dim objExcel As Object 'late binding
'has user selected EmpNum?
If IsNumeric(Me!cmboEmpNum)=TRUE Then
lngEmpNum = Me!cmboEmpNum
Else
MsgBox "Please select an Employee Number."
GoTo Exit_cmdOpenXLS_Click
End If
strExcelPath = "C:\EmpNum.xls"
strSQL = "SELECT * INTO " _
& "[Excel 8.0;Database=" & strExcelPath & "].[" _
& Format(Now(), "yyyymmdd\_hhnnss") _
& "_EmpNum_" & lngEmpNum & "] " _
& "FROM MyRoster "
& "WHERE [Employee Number] = " & lngEmpNum
CurrentDb.Execute strSQL, dbFailOnError
'open xls file
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.Workbooks.Open strExcelPath
Exit_cmdOpenXLS_Click:
If NOT (objExcel Is Nothing) Then Set objExcel = Nothing
Exit Sub
Err_cmdOpenXLS_Click:
MsgBox Err.Description
Resume Exit_cmdOpenXLS_Click
End Sub
There are so many details that could cause this to fail....
-- does not check if xls file is already open
-- assumed [Employee Number] was type Long...