Output Query results and paste into an excel sheet automatically

smpayne

Registered User.
Local time
Today, 10:47
Joined
Sep 29, 2004
Messages
27
Is this possible??

I have a few queries which I run on an Access database, then I manually Copy and Special Paste (csv) into an Excel spreadsheet. This data is then used in a pivot table. I would LOVE to automate this procedure. Is there anyway in doing this with a macro or VBA that me as a total beginner could comprehend??

I have posted a few questions on here in the past week and have received great feedback and assistance. Also, learning very rapidly with your help. I would be forever greatful with anyone having insight on how I could accomplish this.

Any help would be greatly appreciated!

Shawn.
 
Shawn,

This is very possible, as I have done much of this to make some of my daily processes very simple and quick. One question though, since you are fairly new to this, is that when you copy and paste from Access to Excel, can you paste the whole query into a particular spot on the spreadsheet or do you take bits and pieces of the query and copy it into scattered cells within excel?

There are many different ways to do this, but I'll try and keep it simple for you.
 
CSV Paste to Excel

I actually created the Excel workbook so that I always Special Paste into Cell A1 for simplicity and the format never changes. Also, the workbook contains 4 tabs for four different queries, but again, they all get pasted into A1.

Hope that clarifies, and thanks so much for your assistance.

Shawn.
 
Well, yesterday I would have said save all four tables as text files, then use an autoopen function to open them up and run the pivot tables in excel....

But today is a new day and I'm watching this thread with mad keen interest now!!!
 
There will be a few steps in to getting this to work the way you would like. Like I said before, there are a couple of ways to do this.

1. Create a template Excel Workbook, with your Four tabs. I usually name my template file the same as the file I'm going to use and just add template behind it.

2. For the first time, export your data manually to each of the sheets in your template. Do 'Record a macro' then setup your Pivot Tables. Make sure that when you highlight the rows in your spreadsheet, when setting up the pivot tables, that you select more rows that normally are necessary. This gives you room in case your queries produce more rows at any given time. You should be able to record all four sheets into one macro, but be sure that you test it a few times.

I will post back with some more info shortly.
 
Ok.. Assuming that you complete the first two steps, I have created a database containing a form and module that contains the code necessary to accomplish what you are wanting.

Unzip the database, it is in Access 97, and should convert OK to newer versions. Import the form called 'frmExport' and the Module called 'Functions' into your current database.

Open the form up and go into the code. You will have to reference the Microsoft Excel Object Libraty, not sure what version you are using but just check the latest version. If not sure how to do this go into the code page and go to Tools--References(Look for something like Microsoft Excel 9.0 Object Library). Check that and press ok.

Now go to the code behind the Command Button on the form. There are two sections under the Command Button code that you will have to update some info. I highlighted the areas needed to be updated.

1. your File Path & Name and the Template File Name and Macro Name
2. your query names and sheet name from your workbook.


I know that this may be a little more complicated than first thought, but this was the only way that you could get this to work the way you wanted. And if you can learn this, then you will be in good shape. Don't worry I noted all of code behind the form, so hopefully it helps.

Good Luck.
 

Attachments

Last edited:
You are a GOD!!!

Thank you so much, I will begin work right away and get back to you with my results.

Again, thank you!!

Shawn
 
Type Missmatch??

fpendino, I am getting a Type Missmatch in the following location, any thoughts?? (I have highlighted it Red)

'Export data is another function that will export your data.
'Update the query Names to your real Query Names
'Update the Sheet Names accordingly, with the Query it is assiged to
ExportData "01_HRS_POOL_TEAM", "HR_TEAM_POOL"
ExportData "01_HRS_POOL_TEAM", "HR_COLLID"
ExportData "01_HRS_POOL_TEAM", "HRS_TEAM"
ExportData "TEAM_HR_USER_EXP", "HR_COLLID"
ExportData "02_HRS_Utilization", "TimeUtilization"
'ExportData "QUERY4", "SHEET4"
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''


xl.ActiveWorkbook.Save
'The Application.Run will run the Macro(s) that you saved in your spreadsheet
xl.Application.Run "'" & strFileName & "'!" & strMacroName
xl.ActiveWorkbook.Save

'Uncomment/Comment these to close out the workbook
'xl.ActiveWorkbook.Close
'xl.Quit

Set xl = Nothing

End Sub


Private Function ExportData(strQuery As String, strSheet As String)
Dim intR As Integer
Dim rs As Recordset

'After you open that Object/Workbook, you refer to that workbook now as 'xl'. You will
'use it later, but now you have to access your queries through this code and to do so
'you need to use a recordset.

'strQuery is the name of the Query that you passed with the Function. You can also
'use an SQL string.
Set rs = CurrentDb.OpenRecordset(strQuery)
rs.MoveLast 'moves to the last record
rs.MoveFirst 'moves back to the first record
 
I changed my query names to match yours and I'm not getting any errors. Do me a favor. Before you press Run, go to the code and press F8. Then press the run button.

This allows you to STEP through the code. Slowly keep press F8 and let me know when it stops and gives you the error.

Also, If it stops at the place that you indicated, press debug and while that line is highlighted yellow, place your cursor over the strQuery in the Set rs = CurrentDb.OpenRecordset(strQuery) and let me know what value it gives you if any.
 
Errrg

This may sound stupid, but when I try to step into the code with F8, I get that annoying 'Bell' sound. It just won't let me. When I hover the cursor over the highlighted area in debug, nothing comes up. I have attached the complete code for both the Form and the Module:

I really appreciate your patience!

Form:

Private Sub cmdGO_Click()
Dim strFilePath As String
Dim strFileName As String
Dim strFileTemplate As String
Dim strMacroName As String

'''''''''''''UPDATE THIS DATA WITH YOURS''''''''''''''''''''''''''''''
'Fill in the following with your files and path
strFilePath = "\\MINT02\Share\SHARE\SMP\DialerbyTeam\"
strFileName = "DialerbyTeamCurrent.xls"
strFileTemplate = "DialerbyTeamCurrent.xls"
strMacroName = "Update"
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

'This deletes the old file
'Kill strFilePath & strFileName
'This recreates your file with the template
'FileCopy strFilePath & strFileTemplate, strFilePath & strFileName


'This is a custom function I built to set Excel as an object and you can access/export
'to a workbook programmatically. 'openexcel' is stored in a module called Functions.
'This will open the new file that was created previously

openexcel strFilePath & strFileName

'''''''''''''UPDATE THIS DATA WITH YOURS''''''''''''''''''''''''''''''
'Export data is another function that will export your data.
'Update the query Names to your real Query Names
'Update the Sheet Names accordingly, with the Query it is assiged to
ExportData "01_HRS_POOL_TEAM", "HR_TEAM_POOL"
ExportData "01_HRS_POOL_TEAM", "HR_COLLID"
ExportData "01_HRS_POOL_TEAM", "HRS_TEAM"
ExportData "TEAM_HR_USER_EXP", "AVG_HRS_COLL"
ExportData "02_HRS_Utilization", "TimeUtilization"
'ExportData "QUERY4", "SHEET4"
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''


xl.ActiveWorkbook.Save
'The Application.Run will run the Macro(s) that you saved in your spreadsheet
xl.Application.Run "'" & strFileName & "'!" & strMacroName
xl.ActiveWorkbook.Save

'Uncomment/Comment these to close out the workbook
'xl.ActiveWorkbook.Close
'xl.Quit

Set xl = Nothing

End Sub


Private Function ExportData(strQuery As String, strSheet As String)
Dim intR As Integer
Dim rs As Recordset

'After you open that Object/Workbook, you refer to that workbook now as 'xl'. You will
'use it later, but now you have to access your queries through this code and to do so
'you need to use a recordset.

'strQuery is the name of the Query that you passed with the Function. You can also
'use an SQL string.
Set rs = CurrentDb.OpenRecordset(strQuery)
rs.MoveLast 'moves to the last record
rs.MoveFirst 'moves back to the first record

'You can use record count to make sure there are records in your Query/Recordset
If rs.RecordCount < 1 Then
'There are no records
MsgBox "There are no records for " & strQuery
Else
'There are 1 or more records. Now Select the sheet that you will be exporting to
xl.Sheets(strSheet).select

'Now you need to loop through the records. 'intR' was dimmed at beginning of this
'function and will now use it to create a loop or 'For, Next'

'Starts with record 1 and gets the count of records in the recordset so it knows where
'to stop.
For intR = 1 To rs.RecordCount
'Now we need to export the recordset/query to the workbook/object we opened earlier.
'Remember 'rs' refers to the recordset & 'xl' refers to the workbook

'xl.cells(ROW,COLUMN).VALUE = rs.fields(INDEX).
'This is how you will fill in the value of a cell on the workbook. For the ROW you
'will want to add + 1 if you have Headings on your sheet. The INDEX for rs.fields
'refers to the columns of the recordset/query. The first column of the recordset
'starts with the index of zero.

xl.cells(intR + 1, 1).Value = rs.Fields(0)
xl.cells(intR + 1, 2).Value = rs.Fields(1)
xl.cells(intR + 1, 3).Value = rs.Fields(2)
xl.cells(intR + 1, 4).Value = rs.Fields(3)
xl.cells(intR + 1, 5).Value = rs.Fields(4)
'If there are more columns to add than this just follow what I have above

'Moves to the next record
rs.MoveNext
Next intR 'Loops back to For and enters data for the next row

'Once the export is done, this just puts the cursor to A1 on each sheet
xl.range("A1").select

'Clears the recordset
rs.Close
Set rs = Nothing

End If
End Function


Module (Function)

Option Compare Database
Option Explicit

Public xl As Object

Function openexcel(strLocation)

Set xl = CreateObject("Excel.Application")

xl.Visible = True
xl.Workbooks.Open strLocation
End Function
 
Update

Ok, I got some values. In the following statement where I get the MissMatch error 13:

Set rs = CurrentDb.OpenRecordset(strQuery)

It says rs=Nothing and strQuery="01_HRS_POOL_TEAM"

Does this help??
 
Well.. that does help as far as what I was wanting to see, but it doesn't help as far as figuring why the heck it's giving that error message. It seems like it's passing the right info, but for some reason it doesn't like it.

Let's see if you have all of the right references checked. Right now that's my only guess.

I've attached a word doc showing you which ones I have checked. See if that's what you have. Some of the versions of those libraries might be different but that shouldn't matter. That just means they are different versions of Access.
 

Attachments

Update

I just noticed that my Macro name has changed in the Excel workbook. I named it Update, but when I just checked, it renamed it Team1!Update.Update???

Guess that would throw a wrench in it huh??
 
That shouldn't have an affect on what is happening until it tries to execute that macro. The error you're getting is when it opens the recordset, unless this is another issue.

When you view your macros, are you viewing all Macros In: All Open Workbooks? That normally happens when you have more than one workbook open at a time.
 

Users who are viewing this thread

Back
Top Bottom