hi guys, it's been a very long time .
I have copied this code from an old post. This code creates a query then it copies it to an excel sheet. The query works well when i open it manually, but the copy recordset and pasting to excel doesn't work. It opens excel empty. here is the code if someone can help please.
Dim MyDatabase As DAO.Database
Dim MyQueryDef As DAO.QueryDef
Dim MyRecordset As DAO.Recordset
Dim strSQL As String
Dim i As Integer
strSQL = "myquery"
'Step 2: Identify the database and query
Set MyDatabase = CurrentDb
On Error Resume Next
With MyDatabase
.QueryDefs.Delete ("tmpOutQry")
Set MyQueryDef = .CreateQueryDef("tmpOutQry", strSQL)
.Close
End With
'Step 3: Open the query
Set MyRecordset = MyQueryDef.OpenRecordset
'Step 4: Clear previous contents
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
.Workbooks.Add
.Sheets("Sheet1").Select
'Step 5: Copy the recordset to Excel
.ActiveSheet.Range("A2").CopyFromRecordset MyRecordset
'Step 6: Add column heading names to the spreadsheet
For i = 1 To MyRecordset.Fields.Count
xlApp.ActiveSheet.Cells(1, i).Value = MyRecordset.Fields(i - 1).Name
Next i
xlApp.Cells.EntireColumn.AutoFit
End With
I have copied this code from an old post. This code creates a query then it copies it to an excel sheet. The query works well when i open it manually, but the copy recordset and pasting to excel doesn't work. It opens excel empty. here is the code if someone can help please.
Dim MyDatabase As DAO.Database
Dim MyQueryDef As DAO.QueryDef
Dim MyRecordset As DAO.Recordset
Dim strSQL As String
Dim i As Integer
strSQL = "myquery"
'Step 2: Identify the database and query
Set MyDatabase = CurrentDb
On Error Resume Next
With MyDatabase
.QueryDefs.Delete ("tmpOutQry")
Set MyQueryDef = .CreateQueryDef("tmpOutQry", strSQL)
.Close
End With
'Step 3: Open the query
Set MyRecordset = MyQueryDef.OpenRecordset
'Step 4: Clear previous contents
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
.Workbooks.Add
.Sheets("Sheet1").Select
'Step 5: Copy the recordset to Excel
.ActiveSheet.Range("A2").CopyFromRecordset MyRecordset
'Step 6: Add column heading names to the spreadsheet
For i = 1 To MyRecordset.Fields.Count
xlApp.ActiveSheet.Cells(1, i).Value = MyRecordset.Fields(i - 1).Name
Next i
xlApp.Cells.EntireColumn.AutoFit
End With
Last edited: