Access 2013: Saving multiple page PDF from single report - ms-access

I've never posted before and am new to this. I'm using VBA to get a single report to save multiple PDFs. I receive an "Object missing" error message from the code I built from some of the postings here or other sites. I have tried multiple corrections, but each results in either this or a new error. The code is:
Private Sub RunErrors55COPY_Click()
On Error GoTo Err_RunErrors55_Click
Dim MyPath As String
Dim MyFilename As String
Dim uniqueID As Recordset
Dim Report_ID As Field
Dim Db As Database
MyPath = "\\test.net\files\bissvcs\Services\Errors\"
Set Db = CurrentDb()
Set uniqueID = Db.OpenRecordset("ReportIdent01")
'Loop structure may vary depending on how you obtain values
For Each uniqueID In Report_ID
MyFilename = "Bsvc Error " & Report_ID & ".pdf"
'Open report preview and auto-save it as a PDF
DoCmd.OpenReport "Report01 Error Check", acViewPreview, , "uniqueID = " & Report_ID
DoCmd.OutputTo acOutputReport, "Report01 Error Check", acFormatPDF, MyPath & MyFilename, False
'Close the previewed report
DoCmd.Close acReport, "Report01 Error Check"
Next uniqueID
Exit_RunErrors55_Click:
Exit Sub
Err_RunErrors55_Click:
MsgBox Err.Description
Resume Exit_RunErrors55_Click
End Sub
Any ideas and help would be greatly appreciated!

Related

How to Change Record Source with VBA in MS Access Report Macro

All,
In MS Access 2010, I have a table (Today's Settled Jrnls) that is linked to a report. I run the VBA code below to export the report to a pdf on a shared drive.
Public Function exporttopdf()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim MyFileName As String
Dim mypath As String
Dim temp As String
mypath = "S:\Dan\" & Format(Date, "mm-dd-yyyy") & "\"
If Dir(mypath, vbDirectory) = "" Then MkDir mypath
Set db = CurrentDb()
Set rs = CurrentDb.OpenRecordset("SELECT distinct [Settlement No] FROM [Today's Settled Jrnls]", dbOpenDynaset)
Do While Not rs.EOF
temp = rs("[Settlement No]")
MyFileName = rs("[Settlement No]") & ".PDF"
DoCmd.OpenReport "Settlement Report", acViewReport, , "[Settlement No]='" & temp & "'"
DoCmd.OutputTo acOutputReport, "", acFormatPDF, mypath & MyFileName
DoCmd.Close acReport, "Settlement Report"
rs.MoveNext
Loop
Set rs = Nothing
Set db = Nothing
End Function
This works but I'd like to change the [Today's Settled Jrnls] table to a different table [New Jrnls]. The new table is has the exact same columns and setup. However, when I change the table in the select statement above, the code runs but the report is blank. I assume this is because the report (Settlement Report) is still linked to the old table. Do you know how I can link the report to the new table with VBA?
Dan
Simply add a RecordSource call to point to new table after first opening report:
' OPEN REPORT
DoCmd.OpenReport "Settlement Report", acViewReport
' ADJUST SOURCE
Reports![Settlement Report].Report.RecordSource = "SELECT * FROM [New Jrnls]"
' FILTER AND OUTPUT
DoCmd.OpenReport "Settlement Report", acViewReport, , "[Settlement No]='" & temp & "'"
DoCmd.OutputTo acOutputReport, "", acFormatPDF, mypath & MyFileName
DoCmd.Close acReport, "Settlement Report"
You can easily set the Reports recordsource property to a SQL String or bind it to the table
You can even use may of the events like open to set
Me.RecordSource ="SELECT * FROM TBL"
Here check this link: https://learn.microsoft.com/en-us/office/vba/api/access.report.recordsource
For Parfat:

DoCmd.OutputTo not working in MS Access 2010 VBA

I'm having a bit of trouble with VBA in MS Access 2010.
My code is attempting to create a new report for each unique Settlement No. I'm then exporting that report to a folder that's created with today's date and the PDF file is assigned a name with the Settlement No.
In the code below, I keep getting an error in the line with the DoCmd.OutputTo method.
Public Function exporttopdf()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim MyFileName As String
Dim mypath As String
Dim temp As String
mypath = "S:\Settlement Reports\" & Format(Date, "mm-dd-yyyy") & "\"
Set db = CurrentDb()
Set rs = CurrentDb.OpenRecordset("SELECT dbs_eff_date, batch_id_r1, jrnl_name, ledger, entity_id_s1, account_s2, intercompany_s6, trans_amt, dbs_description, icb_name, [Settlement No] FROM [Today's Settled Jrnls]", dbOpenDynaset)
Do While Not rs.EOF
temp = rs("[Settlement No]")
MyFileName = rs("[Settlement No]") & ".PDF"
DoCmd.OpenReport "Settlement Report", acViewReport, , "[Settlement No]='" & temp & "'"
DoCmd.OutputTo acOutputReport, "", acFormatPDF, mypath & MyFileName
DoCmd.Close acReport, "Settlement Report"
rs.MoveNext
Loop
Set rs = Nothing
Set db = Nothing
End Function
If I replace mypath & MyFileName with a hard-coded file path and file name, the macro works so I'm thinking that's where my error is but I can't get it to work correctly.
Any ideas?
Thanks!
Edit:
Here's the specific error:
Run-time error '2501': The OutputTo action was canceled.
You will want to check to make sure the folder exists first, and create it if it doesn't exist. Like this:
If Dir(mypath, vbDirectory) = "" Then MkDir mypath

MS Access DB produces run time error 2473 inconsistently

An Access DB I designed produces the run time error 2473 stating "Object or class does not support the set of events". The error is produced inconsistently, which makes it very hard for me to track it down.
The debugger stops on the following line of code when it appears:
'Open report containing code to create TOC with list of ISINs from above
DoCmd.OpenReport rptName, acViewPreview, , strWhere
Even when the error occurs, this code works fine for some reports, but produces the run time error for others. After opening up the report and the underlying queries in design mode, the run time error sometimes disappears, even though I have changed absolutely nothing in the code, the forms, or even updated the underlying data.
In an attempt to get at this problem, I have restored my DB to an earlier version where I know the problem still existed, but upon opening up the restored version, it no longer has a run time error either!
What could cause this behavior?
UPDATE:
Full code as contained in the Form
Sub cmdFundSelectionReport_Click()
'Gather selected ISIN and pass it to Fund Selection Report
Dim var As Variant
Dim sFund As String
Dim strWhere As String
Dim lst As Access.ListBox
Dim i As Integer
Dim rptType As Integer
'Create list of isin to send to report
Set lst = Me.libFilterSelection
rptType = Me.cmbReportType
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
For i = 0 To lst.ListCount - 1
If Not dict.Exists(lst.Column(1, i)) Then
dict.Add lst.Column(1, i), i
End If
Next i
Dim a As Variant
a = dict.keys
strWhere = "[ISIN] IN("
For i = 0 To dict.Count - 1
strWhere = strWhere & """" & a(i) & ""","
Next i
strWhere = Left(strWhere, Len(strWhere) - 1)
strWhere = strWhere & ")"
'Set dictionary back
Set dict = Nothing
Dim rptName As String
Select Case rptType
Case 2
rptName = "rptRDRSelectionList" '2 is the RDR List
'strWhere = strWhere & " AND Fund_Selection=2"
Case 3
rptName = "rptAsiaSelectionList" '3 Asia
'strWhere = strWhere & " AND Fund_Selection=3"
Case Else
rptName = "rptFundSelectionList" '0 = Fund Selection
'strWhere = strWhere & " AND Fund_Selection=0"
End Select
'Open Report for view
OpenReport rptName, strWhere
'Write Log
WritelogMessage Now & " | User: " & fncUserName & " | Report Created | ReportName: " & rptName
End Sub
Sub OpenReport(rptName As String, strWhere As String)
'Open report containing code to create TOC with list of ISINs from above
DoCmd.OpenReport rptName, acViewPreview, , strWhere
'Click through report so that TOC code is executed
Dim rptCurReport As Report
Set rptCurReport = Screen.ActiveReport
With rptCurReport
Application.DoCmd.SelectObject acReport, .Name
.Visible = True 'switch to false once code is ok
'Go through all pages
SendKeys "{End}", True
DoEvents
Application.DoCmd.SelectObject acReport, .Name
DoCmd.Close acReport, .Name, acSaveNo
End With
rptName = rptName & "TOC" 'Add TOC to get Table of Contents Report
''Check whether "Internal Use Only Flag" is set to true or false
'Dim bInternalUse As Boolean
'bInternalUse = Me.ckbInternalUse.Value
'Call modProcess.ChangeReportPicture("rptFundSelectionListTOC", "picInternalUse", bInternalUse)
'Open final report that includes the TOC as a subreport with same string of ISIN
DoCmd.OpenReport rptName, acViewPreview, , strWhere
SendKeys "{Home}", True
DoEvents
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.

Optimize VBA code that exports to PDF from MS Access

I have two functions that will open and save two diffrent reports based on the same criteria. They are identical except for the refrences:
Function Export_MLR()
On Error GoTo Export_MLR_Err
Dim strReportName As String
DoCmd.OpenReport "Market Rate Notification Final", acViewPreview
strReportName = "S:\National Installations\Market Labor Rates\MLR_INV\MLR\" & Format (Reports![Market Rate Notification Final].Market_ID, "00") & " " & Replace(Reports![Market Rate Notification Final].Product_Code, " / ", "_") & "-" & "Market Rate Notification Final" & "_" & Format(Date, "mmddyy") & ".pdf"
DoCmd.OutputTo acOutputReport, "Market Rate Notification Final", "PDFFormat(*.pdf)", strReportName, False, , , acExportQualityScreen
DoCmd.Close acReport, "Market Rate Notification Final", acSaveNo
Export_MLR_Exit:
Exit Function
Export_MLR_Err:
MsgBox Error$
Resume Export_MLR_Exit
End Function
Then I created this function to select the data and put it into the table that the reports refrence line by line:
Function MassMarket()
On Error GoTo MassMarket_ERR
Dim db As DAO.Database
Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset
'this query creates my rs1 recordset'
DoCmd.SetWarnings (warningsOff)
DoCmd.OpenQuery "mass_market", acNormal, acEdit
DoCmd.SetWarnings (warningsOn)
Set db = CurrentDb()
Set rs1 = db.OpenRecordset("Mass_market_Rate_change")
Set rs2 = db.OpenRecordset("tbl_Form_Auto")
'this checks and clears any records in rs2'
If rs2.EOF = False And rs2.BOF = False Then
rs2.MoveFirst
rs2.Delete
End If
rs1.MoveFirst
'loop goes through and adds 1 line runs reports saves them and deletes line'
Do Until rs1.EOF
Set rs2 = db.OpenRecordset("tbl_Form_Auto")
rs2.AddNew
rs2![MarketID] = rs1![MarketID]
rs2![Product_ID] = rs1![Product_ID]
rs2.Update
Call Export_Invoice
Call Export_MLR
rs1.MoveNext
rs2.MoveFirst
rs2.Delete
Loop
MassMarket_Exit:
Exit Function
MassMarket_ERR:
MsgBox Error$
Resume MassMarket_Exit
End Function
Now all of this worked like a charm but it created, on average 16 .pdf files per minute and I had to create 820 .pdf files(about 50 minutes). If this is the best I can do then I will take it but would love to cut this time in half if possible. Thanks for any and all input. NR
In a comment you indicated the bulk of the time is spent in your functions which export the reports to PDF. I'm uncertain whether we can speed those up.
It seems you open a report, reference a value in that report for use as part of the PDF file name, then call the OutputTo method with the same report name to save it as PDF.
In that situation, I'm uncertain what happens "under the hood" ... whether Access opens a second instance of the report object, or is smart enough to see that you already have an instance open and just use that one instead.
As a test, try to signal Access to use the first report instance. From the online help for the ObjectName parameter of the OutputTo method:
If you want to output the active object, specify the object's type for the ObjectType argument and leave this argument blank.
So what I'm suggesting is try this in your code:
DoCmd.OutputTo acOutputReport, , "PDFFormat(*.pdf)", _
strReportName, False, , , acExportQualityScreen
If Access complains, try it with an empty string for the ObjectName parameter.
DoCmd.OutputTo acOutputReport, "", "PDFFormat(*.pdf)", _
strReportName, False, , , acExportQualityScreen
I don't know how much (or even if) this suggestion will speed up your code. But if you can't speed up those export functions somehow, my hunch is your hope to cut the overall time by half is a shaky proposition.