I have a database in Access that in short is a long list of companies, the products they sell, and there fiscal sales for each on of their products. I would like to write some VBA that will:
1.) Allow me to export a Query to Excel. 2.) Create a new Sheet each time the Query is run 3.) Format the data presented.
I also can't seem to figure out how to paste the data from the query into the new sheet. If any kind soul will help me, it would be very much appreciated.
I know all of this is possible, as I've done a good bit of research on it. But I've run out of time and now just need to figure out where I've gone wrong. This is essential what I have seen so far: (Access VBA How to add new sheets to excel?), (Formatting outputted Excel files from Access using VBA?), (https://www.youtube.com/watch?v=9yDmhzv7nns).
Sub Mysub()
Dim objexcel As Excel.Application
Dim wbexcel As Excel.Workbook
Dim wbExists As Boolean
Dim qdfQUERY2014sales As QueryDef
Dim rsQUERY2014sales As Recordset
Set qdfQUERY2014sales = CurrentDb.QueryDefs("QUERY2014sales")
Set rsQUERY2014sales = qdfQUERY2014sales.OpenRecordset()
Set objexcel = CreateObject("excel.Application")
On Error GoTo Openwb
wbExists = False
Set wbexcel = objexcel.Workbooks.Open("C:\Users\MORTBANKER\Documents\test.xls")
wbExists = True
Openwb:
On Error GoTo 0
If Not wbExists Then
Set wbexcel = objexcel.Workbooks.Add()
End If
CopyToWorkbook wbexcel
End Sub
Private Sub CopyToWorkbook(objWorkbook As Excel.Workbook)
Dim newWorksheet As Excel.Worksheet
Set newWorksheet = objWorkbook.Worksheets.Add()
With newWorksheet
.Range("A1") = rsQUERY2014sales
.columns("A:A").HorizontalAlignment = xlRight
.rows("1:1").Font.Bold = True
End With
'Copy stuff to the worksheet here'
End Sub