How to output multiple PDF files based on record in MS Access? - 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

Related

MS access 3011 Error on Exporting Current Record to Excel

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

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

Looping through a recordset to output Ms-Access report to a pdf file

I'm trying to get pdf file by tenant_id using docmd.outputTo. Unfortunately this routine produce output pdf file that all are in a same single tenant_id. If I remove docmd.outputTo last parameter pathName & fileName then it's require file name through dialogue and output file nicely filtered by tenant_id. Any help would be appreciated.
Here's the query of invoice: SELECT * FROM tblInvoice WHERE tenant_id = CurTenantID()
Public Sub Output()
Dim MyRs As DAO.Recordset
Dim rpt As Report
Dim fileName As String, pathName As String, todayDate As String
pathName = "C:\Users\abzalali\Dropbox\tenant_db\Invoice\"
todayDate = Format(Date, "MMDDYYYY")
Set MyRs = CurrentDb.OpenRecordset("SELECT tenant_id, name, company, email FROM qryEmailClientList")
DoCmd.OpenReport "Invoice", acPreview, , , acHidden
Set rpt = Reports("Invoice")
With MyRs
.MoveFirst
Do While Not .EOF
fileName = "Invoice_" & todayDate & !tenant_id & ".pdf"
rpt.Filter = "[tenant_id] = " & !tenant_id
rpt.FilterOn = True
DoCmd.OutputTo acOutputReport, "Invoice", acFormatPDF, pathName & fileName
.MoveNext
Loop
End With
End Sub
Simply use the DoCmd.OpenReport method to filter report and then leave the report name blank in DoCmd.OutputTo as per the docs:
ObjectName > Optional > Variant: If you want to output the active object, specify the object's type for the ObjectType argument and leave this argument blank.
With MyRs
.MoveFirst
Do While Not .EOF
fileName = "Invoice_" & todayDate & !tenant_id & ".pdf"
DoCmd.OpenReport "Invoice", acViewReport, , "[tenant_id] = " & !tenant_id, acHidden
DoCmd.OutputTo acOutputReport, , acFormatPDF, pathName & fileName
.MoveNext
Loop
End With
Since DoCmd.OutputTo lacks parameters for filtering, the best option is to base the report on a public function to get the current ID.
E.g.
' Function to both set and retrieve the current Tenant ID
Public Function CurTenantID(Optional SetTenantID As Long = 0) As Long
Static TenantID As Long
If SetTenantID > 0 Then
TenantID = SetTenantID
End If
CurTenantID = TenantID
End Function
Your report uses this function in its record source, e.g.
SELECT * FROM tblInvoice WHERE tenant_id = CurTenantID()
And when generating the PDF reports in the loop, you use the SetTenantID parameter:
Public Sub Output()
Dim MyRs As DAO.Recordset
Dim fileName As String, pathName As String, todayDate As String
pathName = "C:\Users\abzalali\Dropbox\tenant_db\Invoice\"
todayDate = Format(Date, "MMDDYYYY")
Set MyRs = CurrentDb.OpenRecordset("SELECT tenant_id, name, company, email FROM qryEmailClientList")
With MyRs
' .MoveFirst -- unneeded after OpenRecordset()
Do While Not .EOF
fileName = "Invoice_" & todayDate & !tenant_id & ".pdf"
Call CurTenantID(!tenant_id)
DoCmd.OutputTo acOutputReport, "Invoice", acFormatPDF, pathName & fileName
.MoveNext
Loop
End With
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.