DoCmd.OutputTo only works on break - ms-access

I've come across a challenging problem with the DoCmd.OutputTo command in VBA Access 2013.
I've got below code which is basically to print a specific report from what is essentially a collection of records of reimbursements. The idea is that one would be able to [export] the active record (from the active form) to a PDF file and then add the scanned invoices to the PDF.
Thereto I would need to build the base file (i.e. the PDF where the invocies are added to) and then run the routine for adding the individual files.
Below code should create the initial PDF file:
Dim rpt as Report
filePath = "<some filepath>"
fName = Me!idDecl & " - (script).pdf"
filePath = filePath & fName
Set rpt = Report_qryDeclInvoice
With rpt
.Filter = "[fltID]= " & Me!id
.FilterOn = True
End With
DoCmd.OpenReport rpt.Name, acViewPreview, , "[fltID]= " & Me!id
DoCmd.OutputTo acOutputReport, rpt.Name, acFormatPDF, filePath, False
DoCmd.Close acReport, "qryDeclInvoice"
If I run the code -without breaks- the report opens as per the filtered argument, however, the subsequent command to output the record to PDF doesn't ?
That is, there appears a dialog box very briefly (can't read what it says) and then execution simply stops, no errors, no faultcodes just a clean break ?
Now for the interesting bit..
If I set a breakpoint on the DoCmd.OutputTo line, and execute the line with F8 the code works more or less flawlessly (see below)?? It appears that the break allows the preview routine to complete first and then run the OutputTo routine.
In addition to above challenge, on some of the reports (i.e. on some reimbursements) it works fine and the file is created yet on others it does not create the initial PDF at all and the code breaks without error codes or fault reporting. Without there being a distinguishable difference between the reports ?
I've tried delaying the OutputTo from the OpenReport function by sleeping it for 1000ms but that doesn't work (even upto 5000ms doesn't yield results)
Also if I remove the open preview line and just execute the OutputTo line, without opening the preview first, it works only when breaking and executing with F8 and again, only on some of the reports not all ?
It seems that the OutputTo command is -at least in my case- somewhat unreliable :-)
Any suggestions ??

OK, found out what was going on;
The faulty reports, that I mentioned, created multiple pages, based on grouping.
A section of VBA code in/on the report, re-created page numbers based on grouping (i.e. restarted page numbering for start of every group.) The execution of this VBA within the report (i.e. on open, or on page) interferes with the execution of the "OutputTo" routine. The above interfered with the OutputTo routine, causing it to break, though not sure why -yet-
Removal of all VBA code within the report solved the issue !!
Some added details:
No need for the preview anymore
set the filter of the report from VBA and open the report through the report object.name
Find below the working code:
Dim rpt as Report
filePath = "<somepath>"
fName = Me!idDecl & "-(script).pdf"
filePath = filePath & fName
'Debug.Print filePath
Set rpt = Report_qryInvoice
With rpt
.Filter = "[fltID]= " & Me!id
.FilterOn = True
End With
'Sleep (5000)
DoCmd.OutputTo acOutputReport, rpt.Name, acFormatPDF, filePath, False, , , acExportQualityScreen

Related

Print multiple copies of report with WHERE clause and without opening Preview

In Datasheet view I created unbounded txtPrintMe field with doubleclick event on it. (because buttons are not allowed in Datasheet view).
I added VBA to print report.
Private Sub txtPrintMe_DblClick(Cancel As Integer)
DoCmd.OpenReport "rptOrder", acViewNormal, , "id = " & Me.txtOrderID
DoCmd.PrintOut , , , , , 2
DoCmd.Close acReport, "rptOrder"
End Sub
When I execute this I get printed 1 copy of my report AND also underlying Form view where my txtPrintMe is located. When I remove PrintOut I get single copy printed out without any issues.
What I want to do: I simply need to print 2 copies of my report without opening Preview mode. I need to do this as efficient (fast printing) as I can.
Probably I want to merge all copies in single document and only then to send it to the printer as single file. But this is optional.

Access Report not Filtering when Others Are

I have a form which allows the user to edit the properties of a filter via some combo boxes, then open a report. The report is opened with
DoCmd.OpenReport rptName, acViewReport, , whereClause, acWindowNormal
'whereClause = "Building = '005'" for instance
Some reports open fine, by which I mean they populate with the filtered info. Others, however, even though they are based off the same in-house template, IGNORE the filter all together and display a report based on ALL data (not the filtered data).
Why would a report ignore the filter? When I edit the reports in design mode after opening them with the form:
Working Report | Non Working Report
Filter: Building = '005' | Filter:
Filter On Load: No | Filter On Load: No
What could be causing the non-working report to not register the filter argument? There's no On Load VBA, nor any VBA, in these reports (except for an Export to PDF and a close button which is copy-paste for each report).
EDIT
Should have checked before, this happens regardless of whether or not the query driving the report is empty (ie the filter is never applied to some reports, regardless of blankness)
Not sure if the code will help, but:
Private Sub btnOpenSummary_Click()
If IsNull(Me.cboSummary) Then
MsgBox "Please select a building for the SUMMARY report."
Exit Sub
End If
strCrit = "Building = '" & Me.cboSummary & "'"
MsgBox strCrit
survArray = getSurveyArray()
For Each Survey In survArray
DoCmd.OpenReport Survey, acViewReport, , strCrit, acWindowNormal
Next Survey
DoCmd.OpenReport "Total Summary", acViewReport, , , , Me.cboSummary
End Sub
My fault.. there was code which had for some reason been linefed all the way down the code page and out of view. There was an On Open which played with the Control Source. It ended up being useless (as the control source only needed to be set once, not every time) but it was disabling the filter for some reason. Anybody else who may have this problem:
Make sure the control source is not being altered in your VBA for the report.
Thanks to those that helped, sorry my information was wrong.
My OnOpen code:
Private Sub Form_Open(Cancel as Integer)
Me.RecordSource = Me.Name
End Sub
It takes the name of the report, which corresponds to a name of a query, and puts it as the recordsource. (I have about 40 reports done this way, so it's dependent on names to make it fast to duplicate for different items).
Removing this made it work perfectly using Access 2010. Not sure if this was a problem specific to my setup or what, but, this change directly fixed it.
This is not a direct solution, but rather a workaround which should almost certainly work. Instead of applying filtering to the report, dynamically change the report data source by passing the where clause as a parameter.
To open the report use:
DoCmd.OpenReport rptName, acViewReport, , , acWindowNormal, whereClause
Note that the whereClause string is being passed as the OpenArgs parameter.
Then in the report VB:
Private Sub Report_Open(Cancel As Integer)
On Error GoTo ReportOpenError
If Not(IsNull(Me.OpenArgs)) Then
Me.RecordSource = Replace(Me.RecordSource,";"," WHERE " & Me.OpenArgs & ";")
End If
Exit Sub
ReportOpenError:
MsgBox "Unable to open the specified report"
Cancel = 1
End Sub
This solution assumes the report RecordSource is defined as a semicolon terminated SQL query (not a query name) and the record source does not already contain any WHERE, GROUP BY, etc., clauses. In those cases, it may be easier to redefine the query from scratch.
This problem may also occur when a report is copied and re-purposed. I had a report that was working fine then made a copy of it and was no longer able to filter it.
Perhaps there is a glitch in Access that causes it to ignore the filter when the report is copied under certain circumstances.
Solution: Instead of copying and re-naming the report, try creating a new report, linking the data source, and copying the fields back into place. If you are dealing with a new report, try re-creating it.

Open only one page of report in Microsoft Access via VBA

What I want to do is very simple, but I'm totally new to VBA. I want to open a report and filter it by page number, so that I could open, say, only page 2. I already have a variable for how many pages it is. I just need to know what to put in the filter argument of the DoCmd.OpenReport function.
The overall goal is to export each page as a separate PDF. If I can do the above, I can do the rest, but if there's something really simple I'm missing, I'm open to suggestions. Thanks.
This is Access 2010 by the way.
To print single pages you can work with the printer object ( http://msdn.microsoft.com/en-us/library/ff837177.aspx ) and the PrintOut command ( http://msdn.microsoft.com/en-us/library/aa220516(v=office.11).aspx ), however, it seems likely that you have a natural break, such as a customer record, and these breaks can be used with the Where argument of OpenReport to easily get separate reports.
EDIT re comments
Very roughly:
sSQL = "SELECT SuitableField FROM Atable ORDER BY Something"
Set rs = CurrentDB.OpenRecordset(sSQL)
Do While Not rs.EOF
DoCmd.OpenReport "TheReport", acViewNormal, , _
"SuitableField='" & rs!SuitableField & "'"
rs.MoveNext
Loop
You may wish to do some work to ensure you are choosing reports with data in them.

Get caption of closed report

I have a custom build print dialog that is used for many reports. Its arguments are the report name, filter string, open args for the report etc. What I would like to do is to display the caption of the report specified for printing on the form. For performance reasons, I would rather not open the report, get the caption and close it again. I would rather get it from the database somehow without actually opening the report itself.
One thing that DOES work is to call the report using it's class name report_some_report.caption but there is no way to do this without with a report name stored in a variable. I would have expected Reports("some_report").caption to work also but it only works for open reports.
Is there a better way to do this or am I going to have to do something like the following? (Which works)
docmd.OpenReport "schedule_simple",acViewDesign,,,acHidden
strCaption = Reports("schedule_simple").Caption
docmd.Close acReport,"schedule_simple"
There's no way to get a report caption from a report without first opening the report or using the report class object (as you know). It's also worth noting that "lightweight" reports (ie, ones whose HasModule property = False) do not have class objects.
You have a couple of options.
You could create a local table with a RptName and RptCaption field and query that. Of course, then you need to keep it updated somehow.
You could write a function that "memoizes" the results, so that you only have to open a given report once each time the program runs. For example:
.
Function GetReportCaption(RptName As String) As String
Static RptCaptions As Collection
If RptCaptions Is Nothing Then Set RptCaptions = New Collection
On Error Resume Next
GetReportCaption = RptCaptions(RptName)
If Err.Number = 0 Then Exit Function
On Error GoTo 0
DoCmd.OpenReport RptName, acViewDesign, , , acHidden
RptCaptions.Add Reports(RptName).Caption, RptName
DoCmd.Close acReport, RptName
GetReportCaption = RptCaptions(RptName)
End Function

Multi-Page vs Multi-PDF Loop problems

I have a form that contains multiple partners that share a "pool". The partners are listed on a subform. After I'm done entering the information, I want a button to run a report for each of the partners with their specific information. But since it's multiple partners and I need one report for each (which I then want to email), I want to use a Loop to go through each of the partners.
EDIT1: Added entire code for review. I do have Option Explicit in and I have compiled it as well.
Private Sub btn_Run_Click()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strSQL As String
strSQL = "Select * FROM Cobind_qryReport WHERE PartPoolName = """ & Me.TopLvlPoolName & """"
Debug.Print "strSQL: " & strSQL
Set db = CurrentDb
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 rs.EOF = False
DoCmd.OutputTo acOutputReport, "Cobind_rptMain", acFormatPDF,_
"K:\OB MS Admin\Postage\CoBind Opportunities\Sent Invites\" _
& rs!CatCode & "_" & rs!PartPoolName "Cobind Invite_" & _
Format(Now(), "mmddyy") & ".pdf"
DoCmd.SendObject acSendReport, "Cobind_rptMain", acFormatPDF, ,_
, , " Cobind Invite", "Please find the cobind invite attached._
Response is needed by " & [RSVP] & ". Thank you.", True
rs.MoveNext
Loop
End If
Exit_PO_Click:
MsgBox ("It didn't work")
rs.Close
Set rs = Nothing
Set db = Nothing
Exit Sub
Err_PO_Click:
MsgBox Err.Description
Resume Exit_PO_Click
End Sub
This should allow me to create a report for each record in my query, save it to my server, then open an email to send it out. Right now, it appears that the [PartPoolName] is hanging up the code because I'm getting a "Microsoft Office Access can't find the field "|" referred to in your expression." If I take out the [PartPoolName], it'll create a PDF with four pages (each page showing a partner), where I want to end up with four separate PDFs.
The first thing you should do is add Option Explicit to the Declarations section of your module.
Then, from the Visual Basic editor's main menu, select Debug->Compile [your project name here]
Fix all the problems the compiler complains about. I suspect one of the compiler's first complaints may be triggered by this section of your code:
rs.MoveFirst
Do While Recordset.EOF = False
Do you have two recordset objects open, or one?
After you fix everything the compiler complains about, try your revised code.
If you get runtime errors, show us the exact error message and which code line is highlighted.
If the part of your code you haven't shown us includes an error hander, you can disable that error handler like so:
'On Error GoTo Err_PO_Click
Error handlers are great for production to shield users from errors. However, during development you really need to be able to identify which code line causes the error.
Alternatively, you can leave your error handler active and select Tools->Options from the editor's main menu. In the Options dialog, select the General tab, then select the "Break on All Errors" radio button and click OK. You can switch that option back to "Break on Unhandled Errors" after you finish your testing.
Update: You wrote: Right now, it appears that the [PartPoolName] is hanging up the code because I'm getting a "Microsoft Office Access can't find the field "|" referred to in your expression."
What is [PartPoolName]? If it's a field in the recordset, you can reference its value as rs!PartPoolName If it's something else, perhaps a global variable, give us more information about it.
Update2: Whenever your current code completes without error, you will hit this:
Exit_PO_Click:
MsgBox ("It didn't work")
Can that be right?
Update3: This OutputTo statement is your issue now, right?
DoCmd.OutputTo acOutputReport, "Cobind_rptMain", acFormatPDF,_
"K:\OB MS Admin\Postage\CoBind Opportunities\Sent Invites\" & _
"Cobind Invite_" & Format(Now(), "mmddyy") & ".pdf"
Cobind_rptMain is a report. It has a RowSource for its data. You're calling OutputTo with that report 4 times (once for each of the 4 rows in the recordset). Yet you expect 4 different versions of that report ... a separate report for each PartPoolName value?
To finish off the fine work by HansUp visit a page on how to print a report for a single record and how to generate reports to attach to emails. See the Emailing reports as attachments from Microsoft Access page.