MS Access export report from another database - ms-access

I am basically trying to do the following (export as report as PDF):
DoCmd.OpenReport report_name, acViewPreview
DoCmd.OutputTo acOutputReport, report_name, acFormatPDF, dest, False
DoCmd.Close acReport, report_name
However I am trying to get it to reference a report object in a completely separate database. How do I modify report_name to get this to work? I've tried "[dbpath].[report_name]" to no avail. The report name has spaces in the name, if that matters.

Create a new Access application session, open the other database, and use that session as the host application for your Application.DoCmd methods.
Dim objAccess As Access.Application
Set objAccess = New Access.Application
objAccess.Visible = True ' <- useful during development
objAccess.OpenCurrentDatabase "C:\wherever\YourDatabase.accdb"
With objAccess.DoCmd
.OpenReport report_name, acViewPreview
.OutputTo acOutputReport, report_name, acFormatPDF, dest, False
.Close acReport, report_name
End With
objAccess.CloseCurrentDatabase
objAccess.Quit
Set objAccess = Nothing

Related

Best way to rename an auto-generated report in MS Access

How do you assign a name to a MS Access report created via CreateReport?
Code creates a dynamic report then adds controls to the report. Last, I want to name/save the report as "Student_Scores_Report01" but it appears that CreateReport auto-generates the name for the report as Report1, Report2, etc. I've run into issues where Access creates a "Report1" but it doesn't actually exist, causing the whole project to be corrupted. This is my best guess at working around this but it seems inefficient:
Dim rpt as Report
Set rpt = CreateReport
Dim ReptNmTemp as String
ReptNmTemp = rpt.name
DoCmd.Save acReport, rpt.Name
DoCmd.Close acReport, rpt.Name
DoCmd.Rename "Student_Scores_Report01", acReport, ReptNmTemp
For Each rpt02 In CurrentProject.AllReports
If rpt02.Name = ReptNmTemp Then
DoCmd.DeleteObject acReport, ReptNmTemp
End If
Next
The For...each loop deletes the auto-generated report and avoids the corruption problem. But is there a better way? Thanks in advance.
Instead of looping you could On Error Resume Next or some other error handler.
Dim rpt as Report
Dim ReptNmTemp as String
Set rpt = CreateReport
ReptNmTemp = rpt.name
DoCmd.Save acReport, ReptNmTemp
DoCmd.Close acReport, ReptNmTemp, acSaveYes
DoCmd.Rename "Student_Scores_Report01", acReport, ReptNmTemp
On Error Resume Next
DoCmd.DeleteObject acReport, ReptNmTemp
Or use acDefault, which is actually a default parameter for both Save and Close, which means if parameter is not provided, acDefault will be used.
Dim rpt as Report
Set rpt = CreateReport
DoCmd.Save , "Student_Scores_Report01"
DoCmd.Close , , acSaveYes

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 2013: Saving multiple page PDF from single report

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!

Split MS-Access reports into pdf's

I got the following VBA code from the web a while ago:
Private Sub btnCreatePDF_Click()
Dim MyPath As String
Dim MyFilename As String
MyPath = "D:\reports\"
MyFilename = "KS1.pdf"
'Open report preview and auto-save it as a PDF
DoCmd.OpenReport "Rpt_KS1", acViewPreview
DoCmd.OutputTo acOutputReport, "", acFormatPDF, MyPath & MyFilename, False 'Change false to true here to auto-open the saved PDF
'Close the previewed report
DoCmd.Close acReport, "Rpt_KS1"
End Sub
It was for use in MS Access to create a single pdf of reports (containing up to 30 pages) and works fine for what i needed. However, i now need to split the report into the 30 or so pages and create a pdf for each of the pages. Any idea how this can be done?
I have a 'username' in the report or can add a unique ID if this helps to split them etc.
Use the 4th parameter (WhereCondition) of Docmd.OpenReport. With the WhereCondition, do exactly what you would normally do when adding a Where to your query, only don't include the word Where. This will make the report only display records that match the WhereCondition.
Retrieve your list of unique identifiers into some sort of a collection, or recordset then do a loop. This example assumes that you have them in a collection called uniqueIds and will almost definitely require some modification by you.
Dim MyPath As String
Dim MyFilename As String
MyPath = "D:\reports\"
'Loop structure may vary depending on how you obtain values
For each uniqueId in uniqueIds
MyFilename = "KS1" & uniqueId & ".pdf"
'Open report preview and auto-save it as a PDF
DoCmd.OpenReport "Rpt_KS1", acViewPreview, , "uniqueField = " & uniqueID
DoCmd.OutputTo acOutputReport, "", acFormatPDF, MyPath & MyFilename, False
'Close the previewed report
DoCmd.Close acReport, "Rpt_KS1"
Next uniqueId
Strictly speaking, this may not result in a different PDF for each page. But it will generate a different PDF for each uniqueID, which might be every page depending on your data.

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.