Programming MS Access report to filter on specific ID - vba

I have a recordset that I'm looping through and would like to create a report that displays information for each user ID in the recordset. I've found many posts that have helped me to write the code, but I cannot figure out why my code keeps opening the report with all user IDs instead of each user ID individually. Here's the code I'm using:
Public Function report()
Dim rs As Recordset
Dim strReportName As String
Dim fileName, pathName As String
pathName = "C:\Users\Joe\Documents"
Set rs = CurrentDb.OpenRecordset("SELECT Add_user, keyer FROM qryProductionReport;")
strReportName = "ProductionReport"
Do While Not rs.EOF
DoCmd.OpenReport strReportName, acViewPreview, , "Add_user = " & rs!Add_user, acHidden
DoCmd.OutputTo acOutputReport, strReportName, acFormatPDF, pathName & strReportName & rs!Keyer & ".PDF"
DoCmd.Close acReport, strReportName
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
End Function
I made sure that my field name Add_user on the report matches the filter that I have in the DoCmd.OpenReport line. I'm using Access 2016. Thanks for the help.

One way is to modify your report to use a TempVars criteria
(e.g. [TempVars]![userId]) as explained here.
You can then use it like this:
Public Function report()
Dim rs As Recordset, strReportName As String
Dim fileName as String, pathName As String
pathName = "C:\Users\Joe\Documents\"
Set rs = CurrentDb.OpenRecordset("SELECT Add_user, keyer FROM qryProductionReport;")
strReportName = "ProductionReport"
Do While Not rs.EOF
TempVars("userId") = rs!Add_user
DoCmd.OutputTo acOutputReport, strReportName, acFormatPDF, pathName & strReportName & rs!Keyer & ".PDF"
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
End Function

Related

Data type mismatch in VBA when filtering form

I have a form with textboxes and one combobox which has the order number, and one command to print the form as PDF and save it to specific folder and then attach it to the attachment column on the same orders table with the same order number selected from my combobox
I made this code below but I am facing this issue
**
It is working and saving PDF file now, but how can I manage to attach the same file to the attachment field in the same table with the same order number row?
I tried the following code to attach but it is not finding the record by Order number
Private Sub Command8_Click()
Dim FileName As String
Dim filepath As String
Dim rst As DAO.Recordset
Dim attachFld As DAO.Recordset
Dim db As DAO.Database, rs As DAO.Recordset, rsAtt As DAO.Recordset2
FileName = Me.Order_Number
filepath = "C:\Users\pc\Desktop\Newfolder\" & FileName & ".pdf"
Forms("Receipt").Filter = "[Order]=" & Me![Order] & ""
Forms("Receipt").FilterOn = True
DoCmd.OutputTo acOutputForm, "Receipt", acFormatPDF, filepath
'DoCmd.Save acForm, "Receipt"
'DoCmd.Close acForm, "Receipt", acSaveNo
' to SAVE ATTACHMENT
'Dim fPath As String: fPath = "C:\Users\india\Desktop\New folder (2)\New folder\"
Set db = CurrentDb
Set rs = db.OpenRecordset("WorkOrders")
If Dir(filepath & rs.Fields("Order").value & ".pdf") <> "" Then
rs.Edit
Set rsAtt = rs.Fields("Attachment").value
With rsAtt
.AddNew
.Fields("Attachment").LoadFromFile (filepath & rs.Fields("ID").value & ".pdf")
.Update
End With
rs.Update
End If
End Sub
**
Private Sub Command8_Click()
Dim FileName As String
Dim FilePatch As String
FileName = "Order_No_" & Me.Order_Number
Filepath = "C:\Users\pc\Desktop\Newfolder" & FileName & ".pdf"
Forms("Receipt").Filter = "[Order]='" & Me![Order] & "'"
Forms("Receipt").FilterOn = True
DoCmd.OutputTo acOutputForm, "Receipt", acFormatPDF, Filepath
'DoCmd.Save acForm, "Receipt"
DoCmd.Close acForm, "Receipt", acSaveNo
End Sub

Print each record to separate pdf file using certain field for filename

I want to print each record to a separate pdf file using certain field for filename.
My code's output does not show the values as shown in the pictures.
Private Sub Command_PDF_Click()
Dim myrs As Recordset
Dim myPDF, myStmt As String
myStmt = "Select distinct Code1 from Query_Certificate_Eng"
Set myrs = CurrentDb.OpenRecordset(myStmt)
Do Until myrs.EOF
myPDF = "C:\Users\93167\Desktop\Output Certificate\" & Format(myrs.Fields("Code1"), "0000000000000") & ".pdf"
DoCmd.OpenReport "Certificate_Eng", acViewPreview, , "Code1" = " & myrs.Fields("").value"
DoCmd.OutputTo objectType:=acOutputReport, objectName:="Certificate_Eng", outputformat:=acFormatPDF, outputfile:=myPDF, outputquality:=acExportQualityPrint
DoCmd.Close
myrs.MoveNext
Loop
myrs.Close
Set myrs = Nothing
End Sub
Problem is in your report opening criteria. So, change it to
"Code1 = '" & myrs!Code1 & "'"

Saving Access Report with Distinct Name

I'm trying to save each individual employees statement using Access Reports. However I'm having issues with getting the Employee Name field to append to the MyFileName variable.
I'm able to export the individual employee reports as a PDF with the following format:
Statement_[EENo].pdf
However, I would like to have this to include the employee name in the following format:
Statement_[Employee Name]_[EENo].pdf
Private Sub Command2_Click()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim MyFileName As String
Dim mypath As String
Dim temp As String
mypath = "FILE LOCATION"
Set db = CurrentDb()
Set rs = db.OpenRecordset("SELECT distinct [EENo] & [Employee Name] FROM [Query]", dbOpenSnapshot)
rs.MoveFirst
Do While Not rs.EOF
temp = rs("EENo" & "Employee Name")
MyFileName = "Statement" & "_" & [Employee Name] & "_" & Format(rs("EENo"), "000000") & ".PDF"
DoCmd.OpenQuery "1 - Query: Firm Admin_EE"
DoCmd.Close acQuery, "1 - Query: Firm Admin_EE", acSaveYes
DoCmd.OpenReport "REPORT", acViewReport, , "[EENo]=" & temp
DoCmd.OutputTo acOutputReport, "", acFormatPDF, mypath & MyFileName
DoCmd.Close acReport, "REPORT"
DoEvents
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub
This should work:
temp = rs("EENo").Value & rs("Employee Name").Value
MyFileName = "Statement_" & rs("Employee Name").Value & "_" & _
Format(rs("EENo").Value, "000000") & ".PDF"
EDIT: I had not really looked at your SQL, and missed that you're combining the two columns in your query. I don't use access but try:
Set rs = db.OpenRecordset("SELECT distinct [EENo] , [Employee Name] FROM [Query]", _
dbOpenSnapshot)

Access VBA - qdf parameters item not found - error 3265

I can't seem to understand what I've done wrong here. I'm getting an error 3265 (Item not found in this collection) at the three lines starting with "qdf.Parameters..." My understanding is that I define the where clause of my sql statement here, but maybe I'm wrong? Pretty new to vba with access so a little confused.
Sub Save_Invoices_Meet_Criteria()
Dim FileName As String
Dim FilePath As String
Dim myStmt As String
Dim Db As DAO.Database
Dim myrs As DAO.Recordset
Set Db = CurrentDb()
Dim qdf As DAO.QueryDef
Set qdf = Db.QueryDefs("qryCreateInvoicesApproved")
qdf.Parameters("[Forms]![frmAccountingDatabaseInput]![Invoice_approved]") = [Forms]![frmAccountingDatabaseInput]![Invoice_approved]
qdf.Parameters("[Forms]![frmAccountingDatabaseInput]![invoice_date]") = [Forms]![frmAccountingDatabaseInput]![Combo272]
qdf.Parameters("[Forms]![frmAccountingDatabaseInput]![Invoice_Type}") = [Forms]![frmAccountingDatabaseInput]![Combo274]
Set myrs = CurrentDb.OpenRecordset("SELECT distinct [reference] from qryCreateInvoicesApproved", 2)
Do Until myrs.EOF
FileName = Me.reference
foldername = Format(Now(), "YYYY-MM-DD")
FilePath = "C:\Users\company\Desktop\Invoicing Database\Save_Test\" & foldername & "\" & FileName & ".pdf"
DoCmd.OpenReport "RPTInvoice", acFormatPDF, FilePath
'DoCmd.OutputTo acOutputReport, , acFormatPDF, FilePath
DoCmd.Close
myrs.MoveNext
Loop
myrs.Close
Set myrs = Nothing
End Sub
My sql statement:
SELECT tblAccountingDatabase.*
FROM tblAccountingDatabase
WHERE (((tblAccountingDatabase.Invoice_approved)=Yes) And ((tblAccountingDatabase.invoice_date)=Forms!frmAccountingDatabaseInput!Combo272) And ((tblAccountingDatabase.Invoice_Type)=Forms!frmAccountingDatabaseInput!Combo274));
Simply add a PARAMETERS line at the beginning of your stored query which you then reference in the VBA querydef object. Then use the Querydef.OpenRecordset() method to pass parameterized query into a recordset object. Right now you are passing named parameters that do not exist:
SQL
PARAMETERS [Approveparam] YesNo, [Dateparam] Datetime, [Typeparam] String;
SELECT DISTINCT [reference]
FROM tblAccountingDatabase
WHERE (((tblAccountingDatabase.Invoice_approved) = [Approveparam])
AND ((tblAccountingDatabase.invoice_date) = [Dateparam])
AND ((tblAccountingDatabase.Invoice_Type) = [Typeparam]));
VBA
...
Dim qdf As DAO.QueryDef
Set qdf = Db.QueryDefs("qryCreateInvoicesApproved")
qdf!Approveparam = [Forms]![frmAccountingDatabaseInput]![Invoice_approved]
qdf!Dateparam = [Forms]![frmAccountingDatabaseInput]![Combo272]
qdf!Typeparam = [Forms]![frmAccountingDatabaseInput]![Combo274]
Set myrs = qdf.OpenRecordset()
...
To pass parameters to a form/report/macro that uses the same paramterized query use DoCmd.SetParameter method. And yes, you need to wrap every value with quotes hence the quote escaping. Also use DoCmd.OutputTo to convert report to PDF:
DoCmd.SetParameter "Approveparam", _
"""" & [Forms]![frmAccountingDatabaseInput]![Invoice_approved] & """"
DoCmd.SetParameter "Dateparam", _
"""" & [Forms]![frmAccountingDatabaseInput]![Combo272] & """"
DoCmd.SetParameter "Typeparam", _
"""" & [Forms]![frmAccountingDatabaseInput]![Combo274] & """"
DoCmd.OpenReport "RPTInvoice", acViewPreview
DoCmd.OutputTo acOutputReport, "RPTInvoice", acFormatPDF, FilePath
It kind of looks like you're trying to force yourself to use a parameter query but not really committed to it. If you don't want to truly use one you can change your SQL structure to use generic parameter names - and then use the qdf.Parameters method to fill the values from your form.
But I think this is the easiest for what you have now.
Replace these lines:
Dim qdf As DAO.QueryDef
Set qdf = Db.QueryDefs("qryCreateInvoicesApproved")
qdf.Parameters("[Forms]![frmAccountingDatabaseInput]![Invoice_approved]") = [Forms]![frmAccountingDatabaseInput]![Invoice_approved]
qdf.Parameters("[Forms]![frmAccountingDatabaseInput]![invoice_date]") = [Forms]![frmAccountingDatabaseInput]![Combo272]
qdf.Parameters("[Forms]![frmAccountingDatabaseInput]![Invoice_Type}") = [Forms]![frmAccountingDatabaseInput]![Combo274]
Set myrs = CurrentDb.OpenRecordset("SELECT distinct [reference] from qryCreateInvoicesApproved", 2)
With this line to open your recordset
Set myrs = qdf.OpenRecordset("SELECT * from qryCreateInvoicesApproved", 2)
Change your query to:
SELECT DISTINCT [reference]
FROM tblAccountingDatabase
WHERE (tblAccountingDatabase.Invoice_approved=[Forms]![frmAccountingDatabaseInput]![Invoice_approved])
AND (tblAccountingDatabase.invoice_date=Forms!frmAccountingDatabaseInput!Combo272)
AND (tblAccountingDatabase.Invoice_Type=Forms!frmAccountingDatabaseInput!Combo274);

Inconsistencies in looping through and creating reports

I have a database with 5 tables, 3 queries, 3 reports (the queries are the recordsets) and three reports each showing the several fields on the recordsets. The problem is, even though they have the same code, one of the sub routines has inconsistent results. It is like it is cycling through each supervisor and creating a report and then doing it again, it's caught in a loop and I can't see where the issue is. Hoping someone can help.
Private Sub cmdFedInvest_Click()
Dim x As String
Dim y As String
Dim StrSQL As String
Dim stWhereStr As String 'Where Condition'
Dim stSection As String 'Selection from drop down list
Dim stfile As String
Dim stDocName As String
Dim StrEmail As String
StrSQL = "SELECT DISTINCTROW [qryActT8_Sup].[Sup], [qryActT8_Sup].Sup_email " & _
"FROM [qryActT8_Sup];"
y = Year(Date)
Dim db As DAO.Database
Dim rst As DAO.Recordset
Set db = CurrentDb
Dim qdTemp As DAO.QueryDef
Set qdTemp = db.CreateQueryDef("", StrSQL)
Set rst = qdTemp.OpenRecordset()
If rst.EOF And rst.BOF Then
MsgBox "No data available for the Ledger Process routine."
Else
Debug.Print rst.Fields.Count
rst.MoveFirst
Do While Not rst.EOF
x = rst![Sup]
StrEmail = rst![Sup_email]
stDocName = "FedInvest - ISSR - T8 Recertification Report"
stWhereStr = "[qryActT8_Sup].[SUP]= '" & x & "'"
stfile = Me.txtLocationSaveFI & "\" & x & " - " & y & " FedInvest Recertification.pdf"
DoCmd.OpenReport stDocName, acPreview, , stWhereStr
'DoCmd.SendObject acSendReport, stDocName, acFormatPDF, StrEmail, , , "2016 FedInvest Recertification", ""
DoCmd.OutputTo acOutputReport, stDocName, acFormatPDF, stfile
DoCmd.Close acReport, stDocName
rst.MoveNext
Loop
End If
rst.Close
Set rst = Nothing
End Sub
You both open the report for preview and for output to PDF.
If only PDF is needed, skip the preview.