MS access 3011 Error on Exporting Current Record to Excel - ms-access

I am working on an export code to copy and export the current record I am viewing to an excel spreadsheet. Below is my code
Private Sub cmdExportFilename_Click()
Dim sFilename As String
Dim StrSQL As String
StrSQL = "Select * FROM [MainData] WHERE ([ID]=" & Me![ID] & ");"
sFilename = "C:\Desktop\exportResults.xlsx"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, StrSQL,
sFilename, True
End Sub
When I run this I get a Run-time error '3011' saying it could not find the object (though it pulls my Select string and correctly identifies I'm viewing record 86 with the error message" and says the object doesn't exist.
My previous code successfully exported data but it outputted the entire query results instead of just the viewed record.
Private Sub cmdExportFilename_Click()
Dim sFilename As String
sFilename = "C:\Users\cpastore\Desktop\exportResults.xlsx"
DoCmd.OutputTo acOutputForm, "OpenComplaintsQuery", acFormatXLSX, sFilename,
AutoStart:=True
End Sub
With Outputto command I do not see where I can select certain things in Parameters. So I thought I would try TransferSpreadsheet command instead.
My end goal ultimately is with the record I am viewing, when I click the button, it exports 6 or 7 fields of 25 that the form displays to an excel spreadsheet where those values Goto a very specific cell location in the sheet. I know with codes above I am a long way from there but I am slowly learning.
Edit: Adding new Code per June7 post suggestion. Ran into another Runtime Error
Private Sub cmdExportfield_Click()
Dim rsGroup As DAO.Recordset
Dim QIMS As String
Dim path As String
path = "C:\Desktop\"
Set rsGroup = CurrentDb.OpenRecordset("SELECT
OpenComplaintsQuery.QIMS# " & "FROM OpenComplaintsQuery GROUP
BY OpenComplaintsQuery.QIMS#", dbOpenDynaset)
Do While Not rsGroup.EOF
QIMS = rsGroup!QIMS#
Dim rsExportSQL As String
rsExportSQL = "Select * FROM OpenComplaintsQuery" & "WHERE
(((OpenComplaintsQuery.QIMS#='" & QIMS & "'))"
Dim rsExport As DAO.QueryDef
Set rsExport = CurrentDb.CreateQueryDef("myexportquerydef",
rsExportSQL)
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9,
"myexportquerydef", path & "exporttest.xlsx", True
CurrentDb.QueryDefs.Delete rsExport.Name
rsGroup.MoveNext
Loop
End Sub

Related

How to output multiple PDF files based on record in MS Access?

I'm new on the MS Access, now I have a report based on the table with 100 records. I want to output the pdf files based on each record. It means each record will have its own single pdf file and the file name will be based on the record's column name.
I have searched on the Internet and I found this vba code is work.
Option Compare Database
Option Explicit
Private Sub Command4_Click()
Dim rsGroup As DAO.Recordset
Dim ColumnName As String, myPath As String
myPath = "C:\test\"
Set rsGroup = CurrentDb.OpenRecordset("SELECT DISTINCT columnName FROM Table_Name", _
dbOpenDynaset)
Do While Not rsGroup.EOF
ColumnName = rsGroup!columnName
' OPEN REPORT, FILTERING RECORDSOURCE BY COLUMN VALUE
DoCmd.OpenReport "Table_Name_Report", acViewPreview, , "Column='" & ColumnName & "'"
' OUTPUT REPORT TO FILE
DoCmd.OutputTo acOutputReport, "Table_Name_Report", acFormatPDF, _
myPath & ColumnName & ".pdf", False
' CLOSE PREVIEW
DoCmd.Close acReport, "Table_Name_Report"
rsGroup.MoveNext
Loop
rsGroup.Close
I never used VBA, and every time I run this code, it will return a window and let me input the column record value. That's not automatically, how to change the code to let it read the record value automatically and populate the pdf?
The way I would do this is to just dynamically set the query the report is based on (i.e. the recordsource) complete with the "columnName". Something like:
(code not run)
Public Sub cmdOpenMyReport_Click()
Dim strSQL As String
Dim rsGroup As DAO.Recordset
Dim ColumnName As String, myPath As String
myPath = "C:\test\"
Set rsGroup = CurrentDb.OpenRecordset("SELECT DISTINCT pharmacyName FROM Sfwy_Patients_New", dbOpenDynaset)
Do Until rsGroup.EOF
ColumnName = rsGroup!pharmacyName
strSQL = "SELECT ... WHERE Column = " & COLUMName & ";" 'copy sql from the report record source and put in the column name as a variable
CurrentDb.QueryDefs("myReportRecordSource").SQL = strSQL
' OUTPUT REPORT TO FILE
DoCmd.OutputTo acOutputReport, "Sfwy_Patients_New_Report", acFormatPDF, _
myPath & ColumnName & ".pdf", False
rsGroup.movenext
Loop
end sub

Parsing data into access from network shared excel workbook

I am parsing a worksheet into Access using the following code:
Sub LoadRates(ByRef TimesheetFile As Excel.Workbook)
On Error GoTo LoadDataCollection_Error
Dim i As Integer
Dim LastRow As Integer
Dim shRates As Excel.Worksheet
Set shRates = TimesheetFile.Worksheets("Rates")
shRates.ShowAllData
LastRow = shRates.Cells(shRates.Rows.Count, 1).End(xlUp).Row
shRates.Cells(1, 4).value = "Current"
Dim db As DAO.Database
Set db = CurrentDb
Dim strSQL As String
Dim dbWb As String
dbWb = "[Excel 12.0;HDR=YES;IMEX=1;Database=" & TimesheetFile.FullName & "].[Rates$A1:i" & LastRow & "]"
strSQL = "SELECT A.[Entity no] AS Entity,Staff AS Name, A.Current as Rates, Company, [2015 BCTC category] AS BCTC_Category,[2015 Rating] As Rating " & _
" INTO fromTimesheet " & _
" FROM " & dbWb & " AS A "
db.Execute strSQL, dbFailOnError
Exit Sub
LoadDataCollection_Error:
... do stuff...
End Sub
my problem is that I have to change the column 4's header to "Current" manually because the title is currently a date value, thus inappropriate for SQL to pick up
shRates.Cells(1, 4).value = "Current"
when I execute this code. sometimes it returns an error message saying it cannot find the field A.Current , and other times it would be able to find it. Is this caused by the workbook being set to Shared?
Any help would be appreciated.
Upon testing, I found out that this error has to do with the excel workbook being "Shared". Once I made the workbook exclusive, the code was able to pick up me editing the row value.
This leads me to believe that when I instantiate an excel workbook object that is being shared. It should be treated as read-only.
Hopefully this is helpful for others.
Yes, your column header is not being effectively saved and connection is using last saved instance.
Consider manually saving it after you make your change. Also, be sure you have write access to save workbook and not in shared/read-only (or alternatively save a different temp workbook for import):
shRates.Cells(1, 4).value = "Current"
TimesheetFile.Save
But also consider using DoCmd.TransferSpreadshet method instead of worksheet connection (which can facilitate "shared" process). Usually one uses a true database for connection and not flatfiles like spreadsheets.
Sub LoadRates(ByRef TimesheetFile As Excel.Workbook)
On Error GoTo LoadDataCollection_Error
Dim i As Integer, LastRow As Integer
Dim shRates As Excel.Worksheet
Set shRates = TimesheetFile.Worksheets("Rates")
shRates.ShowAllData
LastRow = shRates.Cells(shRates.Rows.Count, 1).End(xlUp).Row
shRates.Cells(1, 4).value = "Current"
TimesheetFile.Close True ' SAVES AND CLOSES
DoCmd.TransferSpreadsheet acImport, "fromTimesheet", _
TimesheetFile.FullName, True, "Rates!"
Exit Sub
LoadDataCollection_Error:
... do stuff...
End Sub

How to split a report into multiple PDF files

Let's say I have an hundred page report in Access 2010 that includes lists of names (with some other details), grouped by a variable called NOM_RITIRO.
I would like to output the report into different PDF files, one for each value of the variable used for grouping.
I was trying to figure out how to make this code work:
Sub SplitPdf()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim Source As String
Dim SQL As String
Dim MyPath As String
Dim MyFilename As String
MyPath = "D:\Folder\"
Set db = CurrentDb
SQL = "Select NOM_RITIRO From QueryNominativi Group By NOM_RITIRO"
Set rs = db.OpenRecordset(SQL)
While Not rs.EOF
MyFilename = "TK_" & rs!NOM_RITIRO & ".pdf"
' Apply quotes as NOM_RITIRO is a string.
DoCmd.OpenReport "ElenchiNominativi", acViewPreview, , "NOM_RITIRO = '" & rs!NOM_RITIRO.Value & "'"
DoCmd.OutputTo acOutputReport, , acFormatPDF, MyPath & MyFilename, False
DoCmd.Close acReport, "ElenchiNominativi"
rs.MoveNext
Wend
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub
I got stuck when I try to run the DoCmd.OpenReport.
I get the message box "Enter parameter Value" like if the recordset is not passing any data
Any idea of what I did wrong?
If NOM_RITIRO is not a field in the recordsource of your report called "ElenchiNominativi" (or mis-spelled) then it will prompt you to enter a parameter value.
Similarly, if the recordsource of your report is a query that contains a fieldname not referenced in any of the tables, you will also get this prompt.

Access VBA Loop through Query help

I have a form (Cobind_frmMain) that allows the user to create a pool of titles that are attached to it. So there is a top level Pool Name (TopLvlPoolName) and on a subform, the titles are added to it. What I need is to issue a Report for each of the titles. I have the report and queries all set up. Right now, the report will show all the titles in one file. The titles are in a field called "CatCode".
What I need is the following:
1. Save each title as a PDF and save it to our server.
2. Open email and attach the PDF.
3. Repeat until all titles are done.
EDIT: This is what I have so far for code and the error message I still get is: "Too Few Parameters" on the Set Recordset line. I'm trying to set the parameter in the strSQL line. I want the PartPoolName (in Cobind_qryReport, a query) to equal the TopLvlPoolName on the open form. The SQL for Cobind_qryReport is listed below:
Private Sub btn_Run_Click()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strSQL As String
Set db = CurrentDb
strSQL = "Select * FROM Cobind_qryReport WHERE PartPoolName = " & Me.TopLvlPoolName
Set rs = db.OpenRecordset(strSQL)
On Error GoTo Err_PO_Click
If MsgBox("Do you wish to issue the cobind invites?", vbYesNo + vbQuestion, "Confirmation Required") = vbYes Then
rs.MoveFirst
Do While Recordset.EOF = False
DoCmd.OutputTo acOutputReport, "Cobind_rptMain", acFormatPDF, "K:\OB MS Admin\Postage\CoBind Opportunities\Sent Invites\" & [CatCode] & "_" & [PartPoolName] & "Cobind Invite_" & Format(Now(), "mmddyy") & ".pdf"
DoCmd.SendObject acSendReport, "Cobind_rptMain", acFormatPDF, , , , [CatCode] & "_" & [PartPoolName] & " Cobind Invite", "Please find the cobind invite attached. Response is needed by " & [RSVP] & ". Thank you.", True
Recordset.MoveNext
Loop
End If
Exit_PO_Click:
MsgBox ("It didn't work")
Exit Sub
Err_PO_Click:
MsgBox Err.Description
Resume Exit_PO_Click
End Sub
Cobind_qryReport SQL:
SELECT tblEvents.EventTitle, Cobind_tblPartic.CatCode, Cobind_tblPartic.CodeQty, Cobind_tblPartic.PartPoolName, Cobind_tblTopLvl.RSVP, Cobind_tblPartic.ID
FROM Cobind_tblTopLvl, Cobind_tblPartic INNER JOIN tblEvents ON Cobind_tblPartic.CatCode = tblEvents.EventCode
GROUP BY tblEvents.EventTitle, Cobind_tblPartic.CatCode, Cobind_tblPartic.CodeQty, Cobind_tblPartic.PartPoolName, Cobind_tblTopLvl.RSVP, Cobind_tblPartic.ID
ORDER BY Cobind_tblPartic.ID;
Thank you again for all your help!
You're query Cobind_qryReport has a parameter that you need to set. if you want to know the parameter name try the following code
Dim qdf As QueryDef
Set qdf = CurrentDb.QueryDefs("Cobind_qryReport")
If qdf.Parameters.Count > 0 Then
MsgBox (qdf.Parameters(0).Name)
End If
Update
Since you know you've got a parameter doing select * from Cobind_qryReport it might just be easier to set the parameter and then use the qdf to open the recordset e.g.
Dim rs as DAO.Recordset
Dim qdf As QueryDef
Set qdf = CurrentDb.QueryDefs("Cobind_qryReport")
qdf.Parameters(0).Value = 7832
Set foo = qdf.OpenRecordset()
Note: you can use the parameter name in the place of the ordinal when setting the parametervalue
e.g. qdf.Parameters("Foo").value = 7832

How to generate a PDF file from Access Report?

I'm having trouble trying to export an Access report to PDF format. Basically, I'm working on an old (built in 2001) Access database that uses forms as a user interface. Currently, you can send jobs from a "Jobs" form into an "Invoice" form. Once all the jobs are there, you simply click "Invoice All", specify a date and number of copies and this prints using an Access report as the template.
I've been tasked with adding a save as PDF function, but being a web designer by trade, I have very limited knowledge of Access and VB, but I do know a (very) little amount of ASP.Net and C# (how I got given this task is story for another time...)
In my mind I've approached this by creating a new PDF button on the Access form where they print the invoices. My thoughts are that I could simply duplicate the code for the printing and update to output to a PDF file instead. I can kind of get this working, but not how I'd like.
The code for the print function is below:
Private Sub cmdOpenGroupInvoice_Click()
Dim db As DAO.Database
Dim rsGetCustomerInvoice As DAO.Recordset
Dim rsInvoice As DAO.Recordset
Dim rsInvoiceAll As DAO.Recordset
Dim lngCusID As Long
Dim lngJobNo As Long
Dim iCountInvoice
Dim lngInvoiceNo As Long
Dim iNumberCopies As Integer
Dim sSQLGetInv As String
Dim sSQLInv As String
Dim datInvoiceDate As Date
sSQLGetInv = "SELECT tblJobs.JobNo,tblJobs.NetDespatchRef, tblLoads.Sales, tblLoads.PODName, tblLoads.TotalSales, tblLoads.Cost, tblLoads.Profit, tblJobs.SendToInvoice, tblJobs.Invoiced, tblJobs.MarkForHistory, tblJobs.CustomerID" & vbCrLf _
& "FROM tblJobs INNER JOIN tblLoads ON tblJobs.JobNo = tblLoads.JobNo" & vbCrLf _
& "WHERE (((tblJobs.SendToInvoice)=Yes) AND ((tblJobs.Invoiced)=No) AND ((tblJobs.MarkForHistory)=No));"
Set db = CurrentDb
Set rsGetCustomerInvoice = db.OpenRecordset(sSQLGetInv, dbOpenDynaset)
If rsGetCustomerInvoice.EOF Then
Beep
If MsgBox("There are no jobs to invoice", _
vbCritical + vbOKOnly, _
"No Jobs To Invoice") = vbOK Then
Exit Sub
End If
End If
rsGetCustomerInvoice.MoveLast
Debug.Print rsGetCustomerInvoice.RecordCount
rsGetCustomerInvoice.MoveFirst
Do Until rsGetCustomerInvoice.EOF = True
Set rsGetCustomerInvoice = db.OpenRecordset(sSQLGetInv, dbOpenDynaset)
If rsGetCustomerInvoice.EOF Then
rsGetCustomerInvoice.Close
db.Close
Set rsGetCustomerInvoice = Nothing
Set db = Nothing
DoCmd.Close acForm, "frmInvoiceDate"
Exit Sub
End If
Debug.Print rsGetCustomerInvoice.RecordCount
datInvoiceDate = CVDate(txtInvoiceDate)
lngInvoiceNo = GiveMeAnInvoiceNo()
lngCusID = rsGetCustomerInvoice.Fields!CustomerID
Call AddNewInvoice(lngInvoiceNo, datInvoiceDate, True)
Debug.Print iCountInvoice
lngJobNo = rsGetCustomerInvoice![JobNo]
Call SendThisJobToSageAll(lngCusID, datInvoiceDate, lngInvoiceNo)
Call InvoiceAll(lngCusID, lngInvoiceNo)
Dim strPODName As String
If Not IsNull(rsGetCustomerInvoice!NetDespatchRef) Then
If IsNull(rsGetCustomerInvoice![PODName]) Then
strPODName = " "
Else
strPODName = rsGetCustomerInvoice![PODName]
End If
'Call NetDesTrackingJobCompleate(rsGetCustomerInvoice![NetDespatchRef], rsGetCustomerInvoice![JobNo], strPODName)
End If
iCountInvoice = iCountInvoice - 1
'Debug.Print I
iNumberCopies = txtNumberOfCopies
Do Until iNumberCopies = 0
DoCmd.OpenReport "rptInvoice2", acViewNormal, , "[Invoice No]= " & lngInvoiceNo
iNumberCopies = iNumberCopies - 1
Loop
Form_frmInvoicing.Requery
rsGetCustomerInvoice.MoveNext
Loop
DoCmd.Close acForm, "frmInvoiceDate"
rsGetCustomerInvoice.Close
db.Close
Set rsGetCustomerInvoice = Nothing
Set db = Nothing
End Sub
With my original plan outlined above, I updated the below section to output to PDF:
Do Until iNumberCopies = 0
DoCmd.OpenReport "rptInvoice2", acViewNormal, , "[Invoice No]= " & lngInvoiceNo
DoCmd.OutputTo acOutputReport, "", acFormatPDF, MyPath & MyFilename, True
iNumberCopies = iNumberCopies - 1
Loop
Now this works and it does attempt to output a PDF file. The trouble is, it's runs the report and creates an invoice for every job in the system, rather than applying the report to JUST the jobs which are marked for invoicing.
I'm hoping this is happening because I've put the code in the wrong location, but I have a gut feeling that it's more complicated than that.
It's a bit of a long shot posting it on here, but I really appreciate any help at this point. I've also tried to keep this as short as possible, so if there's any details which aren't clear, I'll help out.
That is quite convoluted, so I think the simplest thing to do, if you do not wish to dive in and tidy up, is to modify the query that the report is based on.
Dim qdf As QueryDef
Set qdf = CurrentDb.QueryDefs("MyReportQuery")
sSQL = "SELECT Whatever FROM MyTable WHERE [Invoice No]= " & lngInvoiceNo
qdf.SQL = sSQL
DoCmd.OutputTo acOutputReport, "rptInvoice2", acFormatPDF, _
MyPath & MyFilename, True
Unless you have Access 2007 with the Save as PDF Add-on or 2010, you may be best installing say, cutePDF, and printing to the PDF printer using DoCmd.PrintOut
I asked the same question a couple of years ago on UtterAccess..
There is a free library to do exactly what you need here: http://www.lebans.com/reporttopdf.htm
My original thread at UA is here : http://www.utteraccess.com/forum/Automatically-PDF-send-t1353547.html
I successfully used the library for a couple of years in several projects, mainly to generate quotes and invoices.
Hope this helps
PG