Private Sub cmdExportToExcel_Click()
Dim oExcel As Object
Dim iRow As Integer
Dim rst As Recordset
'This is where you put your own query to select the fields you want to output
Set rst = CurrentDb.OpenRecordset("Select Field1, Field2, Field3 from Tablename;")
If rst.RecordCount > 0 Then
Set oExcel = CreateObject("Excel.Application")
With oExcel
.Visible = True
.Workbooks.Add
With .Workbooks(.Workbooks.Count).Worksheets(1)
.Cells(1, 4) = "<Stick a title here>"
'populate recordset
rst.MoveLast
rst.MoveFirst
'Create Headings
.Range("A3") = "Heading 1 "
.Range("B3") = "Heading 2"
.Range("C3") = "Heading 3"
'fill in the records starting at row 4
For iRow = 4 To rst.RecordCount + 3
.Cells(iRow, 1) = rst!field1
.Cells(iRow, 2) = rst!field2
.Cells(iRow, 3) = rst!field3
If Not rst.EOF Then rst.MoveNext
Next iRow
iRow = iRow + 1
'---------------------------------------------------------------
'You can change or remove the following to suit your requirements
.Columns("A").ColumnWidth = 10.5
.Range("A3:C" & iRow).Font.Name = "Tahoma"
.Range("A3:C" & iRow).Font.size = "10"
.Range("A3:C" & iRow).Font.Bold = True
.Range("A3:C8").BorderAround Weight:=xlThin
.Range("A3:C8").Borders(xlInsideHorizontal).Weight = xlThin
.Range("A3:C8").Borders(xlInsideVertical).Weight = xlThin
.PageSetup.LeftMargin = 18
.PageSetup.RightMargin = 18
.PageSetup.TopMargin = 18
.PageSetup.BottomMargin = 36
.PageSetup.FitToPagesWide = 1
'-----------------------------------------------------------------
End With
End With
Set oExcel = Nothing
Set rst = Nothing
End If
End Sub