Access: print individual page to pdf, individually named file - ms-access

I'm trying to create a program/macro/VBA in access to print invoices to PDF in individual files. I want the file names to be named with the invoice number as well. But I'm new to Access coding, although I can write code in VBA so I don't know what command I need to do the things above. Here's my plan:
Create a report for the invoices so that it will create 1 invoice on 1 page.
Loop through the table/query (while loop with EOF, for loop with table size)
As long as there's the next record, create a report page for it.
Only print the current page and name it with the corresponding invoice number.
Move on
I know access has a tool to create macro to print to PDF, but it prints everything and doesn't work on individual pages. That's why I think I should use loop. So I want to know:
-Is there a better way to do this?
-If I have to do it this way, then what commands do I need to use.
-I've seen people use these codes:
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set rs = db.OpenRecordset("SELECT distinct [GROUP] FROM [REPORT]", dbOpenSnapshot)
Can you explain what these mean?
Also, I do this at work so I can't install programs. I use Access 2010

For such a problem, I would work with the filtering capabilities of your report...
- Build a query that would prepare all data you need for your invoices (In my case INVOICE)
- Build a report that would print all invoices, based on you query INVOICE
- Use the "Where condition" when opening the report to filter on 1 invoice only
For example, the following code does a .pdf per invoice, name of pdf is ID of invoice. I used INVOICE_ID As the unique ID of the invoice
Option Compare Database
Option Explicit
Private Sub startInvoice_Click()
Dim myrs As Recordset
Dim myPDF, myStmt As String
' Open a record set with a list of invoice number to print
myStmt = "SELECT distinct invoice_id from INVOICE"
Set myrs = CurrentDb.OpenRecordset(myStmt)
' For each invoice, print in a .pdf
Do Until myrs.EOF
' Set the output path of your PDF file invoice
myPDF = "C:\temp\INVOICE_" & Format(myrs.Fields("INVOICE_ID"), "000000") & ".pdf"
' Open the report with the proper where condition
DoCmd.OpenReport "INVOICE", acViewPreview, , "INVOICE_ID = " & myrs.Fields("invoice_id").Value
' Generate the output in pdf
DoCmd.OutputTo objectType:=acOutputReport, objectName:="INVOICE", outputformat:=acFormatPDF, outputfile:=myPDF, outputquality:=acExportQualityPrint
DoCmd.Close ' Close the report
myrs.MoveNext ' read next
Loop
' some cleanup
myrs.Close
Set myrs = Nothing
End Sub
Hope this helps

Related

Access - Open different report from one button

How I can open diferents reports from one button in access if that form that shows me the information has been filtred. For example, in one form I have 2 elements, "t_element"=3 means is ID and name of report is "DNI_CAB", when "t_element"=54 means is Table and name of report is "Table_CAB". And if I filtred another form maybe shows me 8 elements. Thanks!
If I'm understanding this properly, you need to make this table-driven. By that, I mean you need to set up a table with 2 fields; ID and Report Call it tblReports.
Then you would do something like this on the OnClick event of the button:
Dim db as Database
Dim rec as Recordset
Dim MyReport as String
Set db = CurrentDB
'Find the Report you're going to use by filtering by the ID you want
Set rec = db.OpenRecordset("Select Report from tblReports where ID = " & me.txtID & "")
'Fill a variable with the resulting value
MyReport = rec(0)
'Now that we have the report name, open it
DoCmd.OpenReport MyReport
This is all entirely aircode, written off the top of my head, so it probably needs to be altered a little. But it should give you an idea of how to go about writing the code to get this done.

Open correct reports based off of combobox selections

I'm using an Access database in order to store/organize all of the parts for each project. I have 2 comboboxes set up and working correctly: The first is the Customer Name, and once that is selected, the second populates the list of Serial Numbers (project ID numbers) from that Customer. Each project has several components associated with it, in which the reports need to be printed out.
The problem is that most of the component's details are listed in another separate table, so the component number will have to be cross referenced with the table in which it is located and then that report has to be pulled.
This is the table where the comboboxes pull their information from. First the Customer Name, and then the Serial Number associated with that Customer. From there, I want the report from the USER3 table with the associated CATALOG numbers.
For example, here are my combobox selections:
CustomerName - choosing CIPLA would give me SerialNumbers of either EF-1092,96, or 99
I pick Serial Number EF-1096 next - which has CATALOG numbers EDF50-00170 (in the MV table from USER3),EDF12-01114 (in the FIL table), and EDF12-00532 (isn't assigned a table).
So, for EDF50-00170, here's the MV Table with all of the information I want out of it (which the MV report automatically includes):
And here's the corresponding report:
Now is the tricky part where the EDF50-00170, EDF12-01114, and EDF12-00532 reports need to be automatically pulled from the system instead of me having to go find everything manually. This would be the Manual Valve (shown above), Filter, and Misc reports respectively, that have ALL of the Catalog numbers for the category in them.
I already have all of the tables connected to their respective reports, such as this from a previous combobox setup, and I'm assuming this new one will have to be similar:
If partnumberselect.RowSource = "MV" Then
DoCmd.OpenReport "RPTManualValve", acViewPreview, , "CATALOG = '" & Me.partnumberselect.value & "'"
To summarize, I need a group of reports that are associated with a specific Serial Number. Thank you in advance! I'm sorry this is quite the long winded question.
Dim ThisDB As DAO.Database
Dim d As DAO.Recordset
Dim q As String
Set ThisDB = CurrentDb
q = "SELECT CATALOG, User3 FROM [mainSourceTableName] WHERE SerialNumber='" & Me.[SerialNumberSelected] & "'"
Set d = ThisDB.OpenRecordset(q, dbOpenDynaset)
d.MoveFirst
Do While Not d.EOF
Select Case d!User3
Case "MV"
Rem Print MV Report for d!CATALOG
Case "FV"
Rem Print FV Report for d!CATALOG
Rem same for other tables/reports
End Select
d.MoveNext
Loop
d.Close
Example for preview with message box:
DoCmd.OpenReport "RPTManualValve", acViewPreview, , "CATALOG = '" & d!CATALOG & "'"
MsgBox "Test"
DoCmD.Close acReport,"RPTManualValve"

Dynamically combine multiple reports using Sub-Reports - MS Access

I'm attempting to create a master report that I can use to combine multiple other reports into one. Ideally with the end result being a single PDF output.
I've been attempting to use a table to store the names of the reports I would like to populate into the master report and use those to define the SourceObject for the sub reports on load.
Ideally would like the option to have a variable number of sub-reports, so I've been attempting to use the Grouping function to accomplish that. So far the only result I'm getting is having the same report in all groups. I've tried putting the following code into OnLoad and OnCurrent - where txtPageReport is a textbox that is storing the report name.
subReportName = Me.txtPageReport
Me.subReport.SourceObject = subReportName
Any suggestions would be appreciated. Maybe I'm going about this the wrong way completely.
Thanks!
Consider the following two options which does not require table storage of subreports to be called dynamically by master report.
Grouped Report
Insert all subreports into the Group Header section (zero-length Detail section). Then, set each subreport Format property to Can Shrink = Yes and have report page break by Employee Group using Force New Page = Before Section. You can now open report in Print Preview and save as PDF using option on Ribbon.
Non-Grouped Report
Insert all subreports into Detail section (no grouping). Then, dynamically filter report using DoCmd.OpenReport method. Use Where Condition argument to filter by EmployeeID.
Below is a VBA loop to iterate through all employees and then output each individual employee report to PDF. Code can be used for either above grouped or non-grouped report.
Dim db as Database
Dim rst as Recordset
Dim strFile As String
Set db = CurrentDb
Set rst = db.OpenRecordset("SELECT EmployeeID FROM Employees", dbOpenDynaset)
Do While Not rst.EOF
' OPEN FILTERED REPORT IN PRINT PREVIEW '
DoCmd.OpenReport "ReportName", acViewPreview, , "EmployeeID = " & rst!EmployeeID
' OUTPUT REPORT INTO PDF '
strFile = "C:\Path\To\Output\Folder\Employee_" & rst!EmployeeID & ".pdf"
DoCmd.OutputTo acOutputReport, "ReportName", acFormatPDF, strFile, False
rst.MoveNext
Loop
rst.Close
Set rst = Nothing
Set db = Nothing

Access 2007 how use VBA to loop through Query and loop through print reports

I have an existing module that prints a series of reports based on a query (CAP classroom Report gr 5) by looping through another table (School_room_grade). The reports were printed based on a WhereCondition in the module that matched the rows in the School_room_grade table. This process is used so that each school_room_grade combo has their reports all together and resorting of the reports is not required.
One of the reports (CAP Math Gr 5) has been modified and now includes 7 linked subreports which are making the process slow. Each of the subreports is based on the same query but are sorted using different fields. I thought it might be better to unlink the subreports and limit the query to just one school_room_grade combination at at time. When I first made the report without linking the subreports it seemed to run faster. But of course when it is not linked the sorting of reports does not work.
I was thinking that I should make a nested loop with the query on the outside and then loop through the printing of reports. Do you think this would improve the speed?
Here's the original report printing code that worked prior to adding in the linked report.
Option Compare Database
'------------------------------------------------------------
' Print Grade 5 & 6 CAP homeroom reports
'
'------------------------------------------------------------
Sub PrintReports()
Dim rs As DAO.Recordset
Dim rptArr As Variant
Dim rpt As Long
rptArr = Array("CAP MATH GR 5", "CAP ELA GR 5")
Set rs = CurrentDb.OpenRecordset("school_room_query_table_5")
With rs
.MoveFirst
Do While Not .EOF
For rpt = LBound(rptArr) To UBound(rptArr)
DoCmd.OpenReport ReportName:=rptArr(rpt), View:=acViewNormal, _
WhereCondition:="[school_room_grade] = '" & rs!school_room_grade & "'"
Next
.MoveNext
Loop
.Close
End With
MsgBox "Done"
End Sub
The Query that all the reports are based on: [cap classroom report gr 5] - criteria field is [school_room_grade].
The table used for the loop is [school_room_query_table_5] and the matching field is [school_room_grade]
I have never done a loop through a named query - can it be done?
Dim db as Database
Dim rs as RecordSet
Set db = DAO.OpenDatabase("Database path")
Set rs = db.OpenRecordSet("Query name")
For i = 0 To rs.QueryDefs.Count - 1
rs.QueryDefs.Name
next i
Somethings like this should work to loop through the names of the all the query definition names.

Access: How to execute a query and save its result in a report

HI,
I am trying to write a query in vba and to save its result in a report.
I am a beginner. this is what i have tried
can somebody correct me
Dim cn As New ADODB.Connection, rs As New ADODB.Recordset
Dim sql As String
Set cn = CurrentProject.Connection
sql = "Select * from table1 where empno is 0"
rs.Open sql, cn
While Not rs.EOF
' here i think i should save the result in a report but i am not sure how
rs.MoveNext
Wend
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
Also how do i change this query to run this on all tables in a database
IF you are wanting to create a report using MS Access's report generator, you will have to use a Query Object (there might be a way to trick MS Access into running it off of your record set, but it's probably not worth your effort).
You can create the Query Object on the "Database" window. Click the Query button in the objects list, and then click on New. In the resulting editor you can create the query graphically or if you prefer with SQL. Save the query and give it a meaning full name.
Similarly the report can be created on the "Database" window. Click on the Report button and then on New. In the resulting wizard, you'll link the report to the query you just created.
Update: As D.W. Fenton said, you can embed the query right within the Report Object without creating a separate Query Object. My preference is to create one anyway.
The problem with this method is you would have to create a separate query and report for each table.
IF you just want to dump the result out to a text file (to read/print later), then you can do it using recordsets like you are in your VBA code. It will look something like this
'...
dim strFoo as string
dim strBar as string
'...
if not rs.bof then
rd.MoveFirst
end if
While Not rs.EOF
strFoo = rs("foo") 'copy the value in the field
'named "foo" into strFoo.
strBar = rs("bar")
'... etc. for all fields you want
'
'write out the values to a text file
'(I'll leave this an exercise for the reader)
'
rs.MoveNext
Wend
'...
Parsing all of the tables can be done in a loop something like this:
dim strTableName as string
dim db As Database
'...
Set db = CurrentDb
db.TableDefs.Refresh
For Each myTable In db.TableDefs
If Len(myTable.Connect) > 0 Then
strTableName = myTable.Name
'...
'Do something with the table
'...
End If
Next
set db = nothing
=======================UPDATE=======================
It is possible to run an MS-Access Report from a record set. To repease what I said to tksy's question
From Access Web you can use the "name" property of a recordset. You resulting code would look something like this:
In the report
Private Sub Report_Open(Cancel As Integer)
Me.RecordSource = gMyRecordSet.Name
End Sub
In the calling object (module, form, etc.)
Public gMyRecordSet As Recordset
'...
Public Sub callMyReport()
'...
Set gMyRecordSet = CurrentDb.OpenRecordset("Select * " & _
"from foo " & _
"where bar='yaddah'")
DoCmd.OpenReport "myReport", acViewPreview
'...
gMyRecordSet.Close
Set gMyRecordSet = Nothing
'...
End Sub
Q.E.D.
Normally you would design the report based on a data source. Then after your report is done and working properly you use VBA to display or save the report.
To run this for each table in the database, I'd suggest writing a function that looped through CurrentData.AllTables(i) and then called your function above in each iteration
Hope this helps
If you want to simply view the results, you can create a query. For example, here is some rough, mostly untested VBA:
Sub ViewMySQL
Dim strSQL as String
Dim strName As String
'Note that this is not sensible in that you
'will end up with as many queries open as there are tables
For Each tdf In CurrentDB.TableDefs
If Left(tdf.Name,4)<>"Msys" Then
strName = "tmp" & tdf.Name
strSQL = "Select * from [" & tdf.Name & "] where empno = 0"
UpdateQuery strName, strSQL
DoCmd.OpenQuery strName, acViewNormal
End If
Next
End Sub
Function UpdateQuery(QueryName, SQL)
If IsNull(DLookup("Name", "MsysObjects", "Name='" & QueryName & "'")) Then
CurrentDb.CreateQueryDef QueryName, SQL
Else
CurrentDb.QueryDefs(QueryName).SQL = SQL
End If
UpdateQuery = True
End Function
You may also be interested in MDB Doc, an add-in for Microsoft Access 97-2003 that allows you to document objects/properties within an Access database to an HTML file.
-- http://mdbdoc.sourceforge.net/
It's not entirely clear to me what you want to do. If you want to view the results of SQL statement, you'd create a form and set its recordsource to "Select * from table1 where empno is 0". Then you could view the results one record at a time.
If that's not what you want, then I'm afraid I just don't have enough information to answer your question.
From what you have said so far, I don't see any reason why you need VBA or a report, since you just want to view the data. A report is for printing, a form is for viewing and editing. A report is page-oriented and not that easy to navigate, while a form is record-oriented, and allows you to edit the data (if you want to).
More information about what you want to accomplish will help us give you better answers.
Had the same question. just use the clipboard!
select the query results by click/dragging over all field names shown
press ctrl-c to copy to windows clipboard
open a blank document in word and click inside it
press ctrl-v to paste from clipboard.