Saving Access Reports as PDF files - ms-access

I am currently in the process of generating a report in access which, once generated, should be saved to a save location to user puts in.
Here's my block of code.
ReportName = "Appraisal_" & Trim(Str(Year)) & "_" & Me.empnr & "_" & Veilig(Me.empnr) & "_" & Format(Now(), "YYYY_MM_DD_HH_MM_SS")
DoCmd.CopyObject , ReportName , acReport, "rpt_beoordelen"
DoCmd.OpenReport ReportName , acViewPreview, , "EmployeeNr='" & Me.empnr & "' and year=" & Me.Year
DoCmd.OutputTo acOutputReport, "", acFormatPDF, , True
DoCmd.Close acReport, ReportName
This generates and displays the report with the correct values. It asks for save location. And, once given, tries to save the file to given location. It quickly flashes a printing PDF to give location window.
After this the program stops. No file can be found at the given location and the report is still opened. Debugging the application shows me that
DoCmd.Close acReport, ReportName
is never reached. I do not get a errormessage and i have no clue what is going wrong. Could anyone give me a solution to this problem?

If you are having trouble getting DoCmd.OutputTo to work with the "active object" by leaving ObjectName empty (ref: here) then you could try this:
Open the "rpt_beoordelen" report and save its Record Source query as a saved Query named "rpt_beoordelen_base_data". Create a "rpt_beoordelen_data" saved Query with some generic SQL like...
SELECT * FROM rpt_beoordelen_base_data
...then make "rpt_beoordelen_data" the Record Source for the [rpt_beoordelen] report.
Now change the code from your question to something like this:
ReportName = "Appraisal_" & Trim(Str(Year)) & "_" & Me.empnr & "_" & Veilig(Me.empnr) & "_" & Format(Now(), "YYYY_MM_DD_HH_MM_SS")
DoCmd.CopyObject , ReportName , acReport, "rpt_beoordelen"
Dim cdb As DAO.Database
Set cdb = CurrentDb
Dim qdf As DAO.QueryDef
Set qdf = cdb.QueryDefs("rpt_beoordelen_data")
qdf.SQL = "SELECT * FROM rpt_beoordelen_base_data WHERE EmployeeNr='" & Me.empnr & "' and year=" & Me.Year
Set qdf = Nothing
DoCmd.OutputTo acOutputReport, ReportName, acFormatPDF
That will change your invocation of DoCmd.OutputTo to one that does not depend on the "active object" and may yield the results you desire. (FWIW, it's the only way I've gotten this method to work for generating PDF versions of reports.)

Related

Export Multiple named PDF's from MS Access - Data fields not appearing in exported PDF's

First of all.. Many thanks to COmputerVersteher and BankBuilder!!
The export works fine but these data fields do not appear in the export which is needed:
FIRST_NAME, LAST_NAME, DEGREE_TYPE, SCHOOL, HONORS, TITLE, GRADUATION_DATE
Below is the code:
Code:
Private Sub Export_Diploma_letters_Click()
' change NewButton to the name of your new button for printing all students
Dim filename As String
Dim filepath As String
Dim db As DAO.Database
'Dim db As Object
Set db = CurrentDb
Dim rs As DAO.Recordset
' change the name of the table to match your student table vvvvvvvv
Set rs = db.OpenRecordset("SELECT STUDENT_ID, FIRST_NAME, LAST_NAME, DEGREE_TYPE, SCHOOL, HONORS, TITLE, GRADUATION_DATE FROM Humanities", dbOpenSnapshot)
Do Until rs.EOF
' reference the desired field names in the current row
filename = rs("LAST_NAME") & "," & " " & rs("FIRST_NAME") & "," & " " & rs("STUDENT_ID")
filepath = "C:\Users\ddennis1\Desktop\" & filename & ".pdf"
DoCmd.OpenReport "Humanities_MiniDips", acViewPreview, , "[Student_ID]" = rs("STUDENT_ID")
DoCmd.OutputTo acOutputReport, "Humanities_MiniDips", acFormatPDF, filepath
DoCmd.Close acReport, "Humanities_MiniDips", acSaveNo
' This line logs the export for each student, this will help you with
' troubleshooting for specific students if necessary. The log can be found
' by pressing Ctrl + G while in the VBA editor in Access.
Debug.Print "PDF for " & rs("FIRST_NAME") & " " & rs("LAST_NAME") & " exported"
' move to the next record, CRITICAL or else you will loop forever
rs.MoveNext
Loop
' indicate that export is finished
MsgBox "Graduates exported", vbInformation, "Save confirmed"
End Sub
Any ideas and many thanks.

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:

Access VBA for table content as export file Path

i am using the code below to output a form in PDF to folder :\Completions Tracker\Drawings and it works ok, but i would like to set the filepath to refer to a table, so it can be changed by an admin person, when at different project, instead of having to change the VBA code each time.
I would like to change the fixed file path string to refer to table data instead [SettingDrawingFilePathTbl]![Drawing_FilePath].text
but i get a debug when i change the code, any help would be great
Private Sub Command170_Click()
'------Print RFIRegisterInputF form, save input data and close form---------
DoCmd.OutputTo acOutputForm, "RFIRegisterInputF", acFormatPDF, "E:\Completions Tracker\Drawings" & [Forms]![RFIRegisterInputF]![Query_ID] & Format(Date, "ddmmyy") & ".pdf", True
DoCmd.Close acForm, "RFIRegisterInputF", acSaveYes
Use a table to hold the document name (ObjectName) and the corresponding path:
Private Sub Command170_Click()
'------Print RFIRegisterInputF form, save input data and close form---------
Const ObjectName As String = "RFIRegisterInputF"
Dim OutputFile As String
OutputFile = DLookup("[Path]", "[TableName]", "ObjectName = '" & ObjectName & "'") & _
[Forms]![RFIRegisterInputF]![Query_ID] & Format(Date, "ddmmyy") & ".pdf"
DoCmd.OutputTo acOutputForm, ObjectName, acFormatPDF, OutputFile, True
DoCmd.Close acForm, ObjectName, acSaveYes

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

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.