Purdue2479
Registered User.
- Local time
- Today, 05:52
- Joined
- Jul 1, 2003
- Messages
- 52
I am trying to use the below code to export a query from access to excel. I would like to modify the code to paste the data "as values" into an already created excel workbook with formatted columns. I'm not sure how to point to the workbook or keep the excel column formatting when exported. Any help would be appreciated.
Code:
Sub Export_Qry()
Dim db As DAO.Database
Dim rs As DAO.Recordset
'Set db = DAO.DBEngine.Workspaces(0).OpenDatabase( _
"C:\database.mdb")
Set db = CurrentDb
Set rs = db.OpenRecordset("qryWholesaler_Summary_Final", dbOpenSnapshot)
'Start a new workbook in Excel
Dim oApp As New Excel.Application
Dim oBook As Excel.Workbook
Dim oSheet As Excel.Worksheet
Set oBook = oApp.Workbooks.Add
Set oSheet = oBook.Worksheets(1)
'Add the field names in row 1
Dim i As Integer
Dim iNumCols As Integer
iNumCols = rs.Fields.Count
For i = 2 To iNumCols
oSheet.Cells(5, i).Value = rs.Fields(i - 1).Name
Next
'Add the data starting at cell A2
oSheet.Range("B6").CopyFromRecordset rs
'Format the header row as bold and autofit the columns
With oSheet.Range("a1").Resize(1, iNumCols)
.Font.Bold = True
.EntireColumn.AutoFit
End With
oApp.Visible = True
oApp.UserControl = True
'Close the Database and Recordset
rs.Close
'db.Close
End Sub