Function Export2XLS()
Dim oExcel As Object
Dim oExcelWrkBk As Object
Dim oExcelWrSht As Object
Dim bExcelOpened As Boolean
Dim iCol As Integer, iRow As Integer
Dim iTel As Integer, i As Integer
Const xlCenter = -4108
Dim strSQL As String
Dim db As DAO.Database
Dim rst As ADODB.Recordset
'Start Excel
On Error Resume Next
Set oExcel = GetObject(, "Excel.Application") 'Late Binding met Excel
If Err.Number <> 0 Then 'Could not get instance of Excel, so create a new one
Err.Clear
On Error GoTo Error_Handler
Set oExcel = CreateObject("Excel.Application")
bExcelOpened = False
Else 'Excel was already running
bExcelOpened = True
End If
oExcel.ScreenUpdating = False
oExcel.Visible = False 'Keep Excel hidden until we are done with our manipulation
Set oExcelWrkBk = oExcel.Workbooks.Add() 'Start a new workbook
Set oExcelWrSht = oExcelWrkBk.Sheets(1)
Set rst = New ADODB.Recordset
rst.Fields.Append "Testnr", adInteger
rst.Fields.Append "Waardeveld", adVariant
rst.Fields.Append "Waarde", adVariant
rst.Open
With CurrentDb.OpenRecordset("Tdatarangeinvoer", dbOpenSnapshot)
Do While Not .EOF
For i = 1 To .Fields.Count - 1
iTel = iTel + 1
rst.AddNew
rst!Testnr = iTel
rst!Waardeveld = .Fields(i).Name
rst!Waarde = .Fields(i).Value
rst.Update
Next i
.MoveNext
Loop
End With
With rst
If .RecordCount <> 0 Then
.MoveFirst
'Build our Header
For iCol = 0 To .Fields.Count - 1
oExcelWrSht.Cells(1, iCol + 1).Value = .Fields(iCol).Name
Next
With oExcelWrSht.Range(oExcelWrSht.Cells(1, 1), oExcelWrSht.Cells(1, .Fields.Count))
.Font.Bold = True
.Font.ColorIndex = 2
.Interior.ColorIndex = 1
.HorizontalAlignment = xlCenter
End With
'Resize our Columns based on the headings
oExcelWrSht.Range(oExcelWrSht.Cells(1, 1), oExcelWrSht.Cells(1, .Fields.Count)).Columns.AutoFit
Do While Not .EOF
iRow = iRow + 1
For iCol = 0 To .Fields.Count - 1
oExcelWrSht.Cells(iRow + 1, iCol + 1).Value = .Fields(iCol).Value
Next iCol
.MoveNext
Loop
oExcelWrSht.Range("A1").Select
Else
MsgBox "There are no records returned by the specified queries/SQL statement.", vbCritical + vbOKOnly, _
"No data to generate an Excel spreadsheet with"
End If
End With
rst.Close
Set rst = Nothing
End Function