473,756 Members | 8,443 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Exporting Access Query to Excel

9 New Member
I am trying to send the results of a query that runs when I click a button on my form that is based on a parameter query. The code runs without any errors but nothing is exported into my excel spreadsheet and I can't figure out why does anyone see where I went wrong in my code. I am currently using DAO Recordset. Here is what my code looks like:
[code]

Private Sub btnJE_Click() 'Exports qryJE results into excel

On Error GoTo Err_btnJE_Click

MsgBox ExportQuery, vbInformation, "Export Finished"

Exit_btnJE_Clic k:
Exit Sub

Err_btnJE_Click :
MsgBox Err.Description , vbCritical, "Error"
Resume Exit_btnJE_Clic k

End Sub
Public Function ExportQuery() As String
On Error GoTo err_Handler

'Excel object variables
Dim appExcel As Excel.Applicati on
Dim wbk As Excel.Workbook
Dim wks As Excel.Worksheet

Dim sTemplate As String
Dim sTempFile As String
Dim sOutput As String

Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim sSQL As String
Dim IRecords As Long
Dim iRow As Integer
Dim iCol As Integer
Dim iFld As Integer

Const cTabOne As Byte = 1
Const cTabTwo As Byte = 2
Const cStartRow As Byte = 3
Const cStartColumn As Byte = 1

DoCmd.Hourglass True

'Set to break on all errors
Application.Set Option "Error Trapping", 0

'Start with clean file built from template file
sTemplate = CurrentProject. Path & "\JournalEntryT est.xls"
sOutput = CurrentProject. Path & "\JournalEntryF ormTest.xls"
If Dir(sOutput) <> "" Then Kill sOutput
FileCopy sTemplate, sOutput

'Create the Excel Application, Workbook and Worksheet and Database object
Set appExcel = New Excel.Applicati on
appExcel.Visibl e = True
Set wbk = appExcel.Workbo oks.Open(sOutpu t)

sSQL = "SELECT * FROM tblAllPerPayPer iodEarnings " & vbCrLf & "WHERE PG = '" & Forms("frmJE"). Controls("cboAD PCompany").Valu e & "' AND ('LOCATION#') = '" & Forms("frmJE"). Controls("cboLo cationNo").Valu e & "' AND CHECK_DT Between #" & Forms("frmJE"). Controls("txtFr om").Value & "# AND #" & Forms("frmJE"). Controls("txtTo ").Value & "#" & ";"


Set dbs = CurrentDb
Set rst = dbs.OpenRecords et(sSQL, dbOpenSnapshot)
If Not rst.BOF Then
rst.MoveFirst
'For this template, the data must be placed in the appropriate cells of the spreadsheet
Do While Not rst.EOF
With wbk
.Sheets("Journa lEntry").Range( "G3") = rst.Fields("Bra nch Number")
.Sheets("Journa lEntry").Range( "K15:K100") = rst.Fields("Acc ount")
.Sheets("Journa lEntry").Range( "L15:L100") = rst.Fields("Sub Account")
.Sheets("Journa lEntry").Range( "O15:O100") = rst.Fields("Sum OfGROSS")
.Sheets("Journa lEntry").Range( "Q15:Q100") = rst.Fields("Acc ount Description")
.Sheets("Journa lEntry").Range( "G3,K15:K100,L1 5:L100,O15:O100 ,Q15:Q100").Col umns.AutoFit
.SaveAs CurrentProject. Path & "\" & rst.Fields("Bra nch Number") & ".xls"

End With
rst.MoveNext

Loop
rst.Close

ExportQuery = "Total of " & IRecords & " rows processed."

exit_Here:
'Cleanup all objects (resume next on errors)
Set wbk = Nothing
appExcel.Quit
Set appExcel = Nothing
Set rst = Nothing
Set dbs = Nothing
DoCmd.Hourglass False
Exit Function

err_Handler:
ExportQuery = Err.Description
Resume exit_Here
End If
End Function

[\Code]
Oct 30 '07 #1
12 4200
FishVal
2,653 Recognized Expert Specialist
Hi, there.

The first question you should ask yourself having encountered such a kind of problem is - "Does my query return records?"
  • Toggle breakpoint on the next line after
    Expand|Select|Wrap|Line Numbers
    1. sSQL="SELECT .......
  • Get content of sSQL variable, e.g.
    Expand|Select|Wrap|Line Numbers
    1. ? sSQL 
    in immediate VBA window
  • Copypaste it to query builder and run.

Check that first and will proceed with debugging of your code.
Oct 30 '07 #2
TARHEELS721
9 New Member
1. Okay I figured out why nothing was being inputted to the spreadsheet. All the records kept overwriting each other. But I have a new problem after making sure that the query returned values. Only one value is returned to the spreadsheet not all the results produced by the query. Also using the code below I get the error message: {Run-
time error '1004': Application-defined or object-defined error.} This same
message appears when I use the following pieces of code
Expand|Select|Wrap|Line Numbers
  1. .Cells(j,11).Value =
  2. rst.Fields("GL_Acct").Value
  3. .Cell(j,12).Value = rst.Fields("GL_Subacct").Value
  4. .Cell(j,12).Value = rst.Fields("GROSS").Value
  5. .Cell(j,12).Value = rst.Fields("AccountDescription").Value
2. Using this code I get a single record from the query to write to the spreadsheet. Also I receive this error message
"Run-time error '3265': Item not found in this collection." for the
Expand|Select|Wrap|Line Numbers
  1. .Range("O15").Value = rst.Fields("GROSS").Value
I have tried to change the name but nothing works. Any help would be greatly appreciated. I'm not sure what exactly is causing this error I have stepped through the code and everything I'm not sure if I have it coded wrong.

Expand|Select|Wrap|Line Numbers
  1. sSQL = "SELECT  tblAllPerPayPeriodEarnings.GLDEPT, tblGLAllCodes.GL_Acct,
  2. tblGLAllCodes.GL_Subacct, tblGLAllCodes.GL_Dept, tblGLAllCodes.
  3. AccountDescription , tblAllADPCoCodes.BranchNumber, Sum
  4. (tblAllPerPayPeriodEarnings.GROSS) FROM tblAllADPCoCodes, tblGLAllCodes INNER
  5. JOIN tblAllPerPayPeriodEarnings ON tblGLAllCodes.Dept =
  6. tblAllPerPayPeriodEarnings.GLDEPT GROUP BY tblAllPerPayPeriodEarnings.GLDEPT,
  7. tblGLAllCodes.GL_Acct, tblGLAllCodes.GL_Subacct, tblGLAllCodes.GL_Dept,
  8. tblGLAllCodes.AccountDescription, tblAllPerPayPeriodEarnings.PG,
  9. tblAllPerPayPeriodEarnings.[LOCATION#], tblAllADPCoCodes.BranchNumber,
  10. tblAllPerPayPeriodEarnings.CHECK_DT HAVING PG = '" & Forms("frmJE").Controls
  11. ("cboADPCompany").Value & "' AND [LOCATION#] = '" & Forms("frmJE").Controls
  12. ("cboLocationNo").Value & "' AND BranchNumber = " & Forms("frmJE").Controls
  13. ("txtBranchNo").Value & " AND CHECK_DT Between #" & Forms("frmJE").Controls
  14. ("txtFrom").Value & "# AND #" & Forms("frmJE").Controls("txtTo").Value & "#"
  15. & ";"
  16.  
  17. Do Until rst.EOF
  18.    With wbk.Sheets("JournalEntry")
  19.        .Range("G3") = rst.Fields("BranchNumber").Value
  20.        .Range("K15").Value = rst.Fields("GL_Acct").Value
  21.        .Range("L15").Value = rst.Fields("GL_Subacct").Value
  22.        .Range("O15").Value = rst.Fields("GROSS").Value   'not finding value
  23.        .Range("Q15").Value = rst.Fields("AccountDescription").Value
  24.   End With
  25. J = J + 1
  26. rst.MoveNext
  27. Loop
Thanks in advance!
Nov 2 '07 #3
FishVal
2,653 Recognized Expert Specialist
Hi, there.

Though you may expect the name of the field
.... Sum(tblAllPerPa yPeriodEarnings .GROSS)...
will be [GROSS], it isn't so. Access will give it default name like [Expr1].
To explicitely name query field use "AS", e.g.
Expand|Select|Wrap|Line Numbers
  1. SELECT ..... Sum(tblAllPerPayPeriodEarnings.GROSS) AS GROSS ....
  2.  
The code you've posted is not expected to work as it will put all records into the same cells. You have a right decision to use Cells object. Plz post the whole code using .Cells(J,..) references in the loop.

Regards,
Fish
Nov 2 '07 #4
TARHEELS721
9 New Member
Here is the updated version of the code. Now all I need to do is figure out how to get all the results from the query to write into the excel spreadsheet.

Expand|Select|Wrap|Line Numbers
  1. Public Function ExportQuery() As String
  2. On Error GoTo err_Handler
  3.  
  4.     'Excel object variables
  5.     Dim appExcel As Excel.Application
  6.     Dim wbk As Excel.Workbook
  7.     Dim wks As Excel.Worksheet
  8.  
  9.     Dim sTemplate As String
  10.     Dim sOutput As String       'Output string to build up
  11.  
  12.     Dim dbs As DAO.Database     'This is the database
  13.     Dim rst As DAO.Recordset    'Retrieves value of field
  14.     Dim sSQL As String          'SQL Statement
  15.     Dim IRecords As Long
  16.  
  17.     Dim J As Long
  18.  
  19.     DoCmd.Hourglass True
  20.  
  21.     'Set to break on all errors
  22.     On Error Resume Next
  23.  
  24.     'Start with clean file built from template file
  25.     sTemplate = CurrentProject.Path & "\JournalEntryTest.xls"
  26.     sOutput = CurrentProject.Path & "\JournalEntryFormTest.xls"
  27.     If Dir(sOutput) <> "" Then Kill sOutput
  28.     FileCopy sTemplate, sOutput
  29.  
  30.     'Create the Excel Application, Workbook and Worksheet and Database object
  31.     Set appExcel = New Excel.Application            'Assigns objects to variables
  32.     appExcel.Visible = True                         'Makes Excel session visible
  33.     Set wbk = appExcel.Workbooks.Open(sOutput)
  34.  
  35. sSQL = "SELECT  tblAllPerPayPeriodEarnings.GLDEPT, tblGLAllCodes.GL_Acct, tblGLAllCodes.GL_Subacct, tblGLAllCodes.GL_Dept, tblGLAllCodes.AccountDescription , tblAllADPCoCodes.BranchNumber, Sum(tblAllPerPayPeriodEarnings.GROSS) As GROSS FROM tblAllADPCoCodes, tblGLAllCodes INNER JOIN tblAllPerPayPeriodEarnings ON tblGLAllCodes.Dept = tblAllPerPayPeriodEarnings.GLDEPT GROUP BY tblAllPerPayPeriodEarnings.GLDEPT, tblGLAllCodes.GL_Acct, tblGLAllCodes.GL_Subacct, tblGLAllCodes.GL_Dept, tblGLAllCodes.AccountDescription, tblAllPerPayPeriodEarnings.PG, tblAllPerPayPeriodEarnings.[LOCATION#], tblAllADPCoCodes.BranchNumber, tblAllPerPayPeriodEarnings.CHECK_DT HAVING PG = '" & Forms("frmJE").Controls("cboADPCompany").Value & "' AND [LOCATION#] = '" & Forms("frmJE").Controls("cboLocationNo").Value & "' AND BranchNumber = " & Forms("frmJE").Controls("txtBranchNo").Value & " AND CHECK_DT Between #" & Forms("frmJE").Controls("txtFrom").Value & "# AND #" & Forms("frmJE").Controls("txtTo").Value & "#" & ";"
  36.  
  37.     Set dbs = CurrentDb                                 'Opens database
  38.     Set rst = dbs.OpenRecordset(sSQL, dbOpenSnapshot)   'Sets the record set to the query
  39.  
  40. Do Until rst.EOF
  41.     With wbk.Sheets("JournalEntry")
  42.     J = 15
  43.     IRecords = IRecords + 1
  44.         .Range("G3") = rst.Fields("BranchNumber").Value
  45.         .Cells(J, 11).Value = rst.Fields("GL_Acct").Value
  46.         .Cells(J, 12).Value = rst.Fields("GL_Subacct").Value
  47.         .Cells(J, 15).Value = rst.Fields("GROSS").Value
  48.         .Cells(J, 17).Value = rst.Fields("AccountDescription").Value
  49.  
  50.     End With
  51. J = J + 1
  52. rst.MoveNext
  53. Loop
  54.  
  55. 'wbk.Save
  56. wbk.Close True
  57.  
  58.  
  59.     ExportQuery = "Total of " & IRecords & " rows processed."
  60.  
  61. exit_Here:
  62. 'Cleanup all objects (resume next on errors)
  63. Set wbk = Nothing
  64. appExcel.Quit
  65. Set appExcel = Nothing
  66. Set rst = Nothing
  67. Set dbs = Nothing
  68. DoCmd.Hourglass False
  69. Exit Function
  70.  
  71. err_Handler:
  72.     ExportQuery = Err.Description
  73.     Resume exit_Here
  74. End Function
Nov 5 '07 #5
FishVal
2,653 Recognized Expert Specialist
Hi, there.

Take line 42
J=15
and put it before line 40
Do Untill ....
Nov 6 '07 #6
TARHEELS721
9 New Member
I was wondering if there is a way to total within a totals query. I mean the results of my query list everything out depending on account numbers and check date. What I want to do is have the amount be totalled based on account number and sub account number. So I dont have multiple entries of the same account and sub account number.

Hi, there.

Take line 42
J=15
and put it before line 40
Do Untill ....
Nov 6 '07 #7
TARHEELS721
9 New Member
View next message wrong post
Nov 7 '07 #8
TARHEELS721
9 New Member
I have a query that produces this output and I want to be able to get the sum of a field based on the Account & Subaccount matching. Here is what the query result looks like.
Account Subaccount AcctDesc SumOfGross Check Date
60110 0100 ...... 4160 9/7/2007
60110 0100 ...... 4160 9/21/2007
60810 0900 ...... 842 9/21/2007
60810 0900 ...... 843.5 9/7/2007

This is the results that appear on the excel spreadsheet:
Account Subaccount AcctDesc SumOfGross
60110 0100 ...... 8320
60810 0900 ...... 1684
60810 0900 ...... 1687

I would like to have the result look like this in my spreadsheet
Account Subaccount AcctDesc SumOfGross
60110 0100 ...... 8320
60810 0900 ...... 1685.5


I was wondering if there is a way to total within a totals query. I mean the results of my query list everything out depending on account numbers and check date. What I want to do is have the amount be totalled based on account number and sub account number. So I dont have multiple entries of the same account and sub account number.
Nov 7 '07 #9
TARHEELS721
9 New Member
Is there a way to automate other rows in excel based on the number of entries that are produced by the query. For example have a column named line increment by one for each result of the query that is exported to excel.
Nov 7 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

3
9247
by: sridevi | last post by:
Hello How to export data from ms-access database to excel worksheet using ASP. mainly i need to export data to multiple worksheets. it is very urgent to us. i have a sample code which works only exporting to single worksheet. but i need to export data to multiple worksheets. it is very urgent to us. so please help me in code.
4
3949
by: D | last post by:
I've created a report with many subreports of aggregate data. I want my client to be able to export this data to Excel to make her charts, etc. Only one problem: one of the fields is a "SchoolYear" TEXT field that contains data such as 2000/01, 2001/02, etc. If I export a Query with this kind of data to Excel, it gives me the text value of this field; however, when I export a Report bound to this TEXT field, Excel gives me the values 36526,...
2
8013
by: Kenneth | last post by:
How do I remove the limitation in Access that deny me from exporting 24000 rows and 17 columns (in a query) into Excel? Kenneth
1
7798
by: Suffrinmick | last post by:
Hello Everyone I've built a database using Access 2000 which includes a query which is built using a form containing filters. No problem. When I export the results of the query to excel, (File > Export > Save as type: Microsft Excel 97-2000) one of the fields, which is a memo field type, loses any data over the first 255 characters. How do I get all the data into excel? Thanks
21
6241
by: bobh | last post by:
Hi All, In Access97 I have a table that's greater than 65k records and I'm looking for a VBA way to export the records to Excel. Anyone have vba code to export from access to excel and have the code use multiple excel tabs within a workbook???? Anyone have vba code that would create a temp table write 65,000 records to it, export those to excel, clean the temp table, append the next 65,000 records, export it to excel with a different...
16
10073
by: robertmeyer1 | last post by:
Hey, I am working on creating a query which will export the information to excel. I have a specific excel document which has line by line items (corresponds to access query). Here's the layout of the excel doc. Each row is a different line item. Each column is a different entity. So there are about 750 entities which will be exported to this excel doc. (1 entity per column). For access, I have the same information as the excel...
6
2185
by: jpatchak | last post by:
Hi, I have kind of a strange problem. I have a report that I need to export to excel. The report opens fine in Access and when I export it or click on "Analyze It with Microsoft Office Excel," I get the dialog that says it's exporting page n of total to file such and such. I get no error message. However, no Excel file is created. I've tracked down the problem to one of my fields on the report. It is a field called "ExpectedRate," with...
2
2054
by: eskelies | last post by:
Hello all, I have data, which is separated into account numbers (ie. 10, 20, 30), but it exists in one query. Right now, I have an access macro "transferspreadsheet," which is exporting all the account numbers into one worksheet. My question: How can I go about exporting data from the query into excel, so that each different fund number has it's own worksheet and it's corresponding data? Thank you. Your assistance would be greatly...
4
2393
by: myemail.an | last post by:
Hi all, I use Access 2007 and have the following problems: when exporting banal select queries (either to Excel or to a csv file) I find that exporting often doesn't work and creates a file with the WHOLE dataset, i.e. including those rows which the criteria of the query excluded. For example: let's say I have a database with sales by region. I create a select query to only show sales from Europe. The query runs
9
2780
by: QCLee | last post by:
Sir can you help me to transfer my Access Query to MS excel? i have a command button on the form to export the parameter query named "HVACWindwardQuery" to excel spreadsheet and i got the codes from searching on the internet and books but the problem is when i run the command button "Export" it just only open the Blank Spreadsheet, no data at all that it came from my query named "HVACWindwardQuery" and there's an error on it...
0
9462
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9886
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9857
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9722
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7259
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6542
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5155
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3817
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2677
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.