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]
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
- Get content of sSQL variable, e.g.
in immediate VBA window - Copypaste it to query builder and run.
Check that first and will proceed with debugging of your code.
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 - .Cells(j,11).Value =
-
rst.Fields("GL_Acct").Value
-
.Cell(j,12).Value = rst.Fields("GL_Subacct").Value
-
.Cell(j,12).Value = rst.Fields("GROSS").Value
-
.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 - .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. - sSQL = "SELECT tblAllPerPayPeriodEarnings.GLDEPT, tblGLAllCodes.GL_Acct,
-
tblGLAllCodes.GL_Subacct, tblGLAllCodes.GL_Dept, tblGLAllCodes.
-
AccountDescription , tblAllADPCoCodes.BranchNumber, Sum
-
(tblAllPerPayPeriodEarnings.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 & "#"
-
& ";"
-
-
Do Until rst.EOF
-
With wbk.Sheets("JournalEntry")
-
.Range("G3") = rst.Fields("BranchNumber").Value
-
.Range("K15").Value = rst.Fields("GL_Acct").Value
-
.Range("L15").Value = rst.Fields("GL_Subacct").Value
-
.Range("O15").Value = rst.Fields("GROSS").Value 'not finding value
-
.Range("Q15").Value = rst.Fields("AccountDescription").Value
-
End With
-
J = J + 1
-
rst.MoveNext
-
Loop
Thanks in advance!
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. -
SELECT ..... Sum(tblAllPerPayPeriodEarnings.GROSS) AS GROSS ....
-
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
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. - Public Function ExportQuery() As String
-
On Error GoTo err_Handler
-
-
'Excel object variables
-
Dim appExcel As Excel.Application
-
Dim wbk As Excel.Workbook
-
Dim wks As Excel.Worksheet
-
-
Dim sTemplate As String
-
Dim sOutput As String 'Output string to build up
-
-
Dim dbs As DAO.Database 'This is the database
-
Dim rst As DAO.Recordset 'Retrieves value of field
-
Dim sSQL As String 'SQL Statement
-
Dim IRecords As Long
-
-
Dim J As Long
-
-
DoCmd.Hourglass True
-
-
'Set to break on all errors
-
On Error Resume Next
-
-
'Start with clean file built from template file
-
sTemplate = CurrentProject.Path & "\JournalEntryTest.xls"
-
sOutput = CurrentProject.Path & "\JournalEntryFormTest.xls"
-
If Dir(sOutput) <> "" Then Kill sOutput
-
FileCopy sTemplate, sOutput
-
-
'Create the Excel Application, Workbook and Worksheet and Database object
-
Set appExcel = New Excel.Application 'Assigns objects to variables
-
appExcel.Visible = True 'Makes Excel session visible
-
Set wbk = appExcel.Workbooks.Open(sOutput)
-
-
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 & "#" & ";"
-
-
Set dbs = CurrentDb 'Opens database
-
Set rst = dbs.OpenRecordset(sSQL, dbOpenSnapshot) 'Sets the record set to the query
-
-
Do Until rst.EOF
-
With wbk.Sheets("JournalEntry")
-
J = 15
-
IRecords = IRecords + 1
-
.Range("G3") = rst.Fields("BranchNumber").Value
-
.Cells(J, 11).Value = rst.Fields("GL_Acct").Value
-
.Cells(J, 12).Value = rst.Fields("GL_Subacct").Value
-
.Cells(J, 15).Value = rst.Fields("GROSS").Value
-
.Cells(J, 17).Value = rst.Fields("AccountDescription").Value
-
-
End With
-
J = J + 1
-
rst.MoveNext
-
Loop
-
-
'wbk.Save
-
wbk.Close True
-
-
-
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 Function
FishVal 2,653
Recognized Expert Specialist
Hi, there.
Take line 42
J=15
and put it before line 40
Do Untill ....
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 ....
View next message wrong post
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.
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.
Sign in to post your reply or Sign up for a free account.
Similar topics |
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.
|
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,...
|
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
|
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
|
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...
| |
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...
|
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...
|
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...
|
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
|
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...
|
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...
| |
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...
|
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,...
|
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...
|
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...
|
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();...
|
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...
| |
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
|
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...
| |