Errors ms access vba email report - vba

I keep getting an error when I run this code.
Sub SendEmailMaturing()
Dim rs As DAO.Recordset
Dim db As Database
Dim strSQL As String
Set db = CurrentDb
strSQL = "SELECT * FROM qRespCodeEmail"
Set rs = CurrentDb.OpenRecordset(strSQL)
If Not rs.BOF And Not rs.EOF Then
rs.MoveFirst
Do While Not rs.EOF
'Debug.Print rs.Fields("RMName")
DoCmd.OpenReport "Maturing Loans in 90", acViewPreview, , "RespName = " & rs!RMName
DoCmd.SendObject acSendReport, "Maturing Loans in 90", acFormatPDF, rs!Email, , , "Maturing Loans", "Kindly take a look and send me an update on the status of matured loans.", True
DoCmd.Close acReport, "Maturing Loans in 90", acSaveNo
rs.MoveNext
Loop
End If
rs.Close
Set rs = Nothing
End Sub

If you are filtering on a text field, use apostrophe delimiters for parameter:
DoCmd.OpenReport "Maturing Loans in 90", acViewPreview, , "RespName = '" & rs!RMName & "'"
Use # for date/time fields, nothing for number type.
Could reduce amount of data pulled by including just necessary fields in SQL statement. Appears you need only RMName and Email.

Related

Access Not Printing to the Printer Chosen

I'm having an issue with an access form/report as it's not printing to the printer I've chosen from a combobox (that lists all the available printers).
I do know that I did create the report through the designer with the printer zebra-01 set and I think this is what might be causing the problem.
I have the following code to print labels from the report:
'Option Compare Database
Private Sub btnPrint_Click()
'Validate Input Given. If the input is less than or equal to 0 discard the print command.
'Two If statements, one for validating the input type and if the input is a positive number.
If IsNull(Me.txtNumberOfLabels) Or Not IsNumeric(Me.txtNumberOfLabels.Value) Then
MsgBox "O valor introduzido não é um valor numérico.", _
vbOKOnly, "Erro"
DoCmd.GoToControl "txtNumberOfLabels"
Exit Sub
End If
If Me.txtNumberOfLabels.Value <= 0 Then
MsgBox "O número de etiquetas a imprimir deve ser superior a 0", _
vbOKOnly, "Erro"
DoCmd.GoToControl "txtNumberOfLabels"
Exit Sub
End If
Dim availablePrinters As Printer
Dim selectedPrinter As String
DoCmd.GoToControl "cbPrintersList"
selectedPrinter = Me.cbPrintersList.Text
For Each availablePrinters In Application.Printers
If availablePrinters.DeviceName = selectedPrinter Then
Set Application.Printer = availablePrinters
Exit For
End If
Next availablePrinters
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim lastLabelRecordIndex_Part1 As String
Dim lastLabelRecordIndex_Part2 As String
Dim lastLabelRecordIndex_Part3 As String
Dim oldLastLabelRecordIndex_Part1 As String
Dim oldLastLabelRecordIndex_Part2 As String
Dim oldLastLabelRecordIndex_Part3 As String
Dim strSQL As String
Set db = CurrentDb
strSQL = "SELECT MAX(Pre_SSCC) As MaxRecord FROM SSCC_Gen"
Set rs = db.OpenRecordset(strSQL, dbOpenSnapshot)
oldLastLabelRecordIndex_Part1 = CStr(Left(rs("MaxRecord"), 8))
oldLastLabelRecordIndex_Part2 = CStr(Mid(rs("MaxRecord"), 9, 4))
oldLastLabelRecordIndex_Part3 = CStr(Right(rs("MaxRecord"), 5))
rs.Close
db.Close
Dim labelRecordIndex As Long
DoCmd.SetWarnings False
For labelRecordIndex = CLng(oldLastLabelRecordIndex_Part3) To CLng(oldLastLabelRecordIndex_Part3) + Me.txtNumberOfLabels.Value - 1
DoCmd.RunSQL "INSERT INTO SSCC_GenCount (Data) VALUES (#" & Format(Now(), "dd/mm/yyyy") & "#)"
Next labelRecordIndex
DoCmd.SetWarnings True
Set db = CurrentDb
Set rs = db.OpenRecordset(strSQL, dbOpenSnapshot)
lastLabelRecordIndex_Part1 = CStr(Left(rs("MaxRecord"), 8))
lastLabelRecordIndex_Part2 = CStr(Mid(rs("MaxRecord"), 9, 4))
lastLabelRecordIndex_Part3 = CStr(Right(rs("MaxRecord"), 5))
rs.Close
db.Close
Dim oldLastLabelRecordIndex As String
Dim lastLabelRecordIndex As String
oldLastLabelRecordIndex = oldLastLabelRecordIndex_Part1 & oldLastLabelRecordIndex_Part2 & CStr(oldLastLabelRecordIndex_Part3 + 1)
lastLabelRecordIndex = lastLabelRecordIndex_Part1 & lastLabelRecordIndex_Part2 & lastLabelRecordIndex_Part3
DoCmd.SetWarnings False
DoCmd.OpenReport Report_Labels_SSCC_Gen.Name, acViewPreview, , "Pre_SSCC BETWEEN '" & CStr(oldLastLabelRecordIndex) & "' AND '" & CStr(lastLabelRecordIndex) & "'", acHidden
Set Report_Labels_SSCC_Gen.Printer = Application.Printers(Me.cbPrintersList.ListIndex)
'MsgBox Report_Labels_SSCC_Gen.Printer.DeviceName
DoCmd.OpenReport Report_Labels_SSCC_Gen.Name, , , "Pre_SSCC BETWEEN '" & CStr(oldLastLabelRecordIndex) & "' AND '" & CStr(lastLabelRecordIndex) & "'", acHidden
DoCmd.Close acReport, Report_Labels_SSCC_Gen.Name, acSaveNo
DoCmd.SetWarnings True
End Sub
And this is the code to populate the combobox with the list of available printers, as soon as the form comes up:
Private Sub Form_Load()
Dim printerIndex As Integer
For printerIndex = 0 To Application.Printers.Count - 1
Me.cbPrintersList.AddItem (Application.Printers(printerIndex).DeviceName)
Next printerIndex
DoCmd.GoToControl "cbPrintersList"
End Sub
Now, according to dozens of articles I've read the whole day, the following bit of code should set the printer I want to print to, but it still keeps sending to the zebra-01 printer:
DoCmd.OpenReport Report_Labels_SSCC_Gen.Name, acViewPreview, , "Pre_SSCC BETWEEN '" & CStr(oldLastLabelRecordIndex) & "' AND '" & CStr(lastLabelRecordIndex) & "'", acHidden
Set Report_Labels_SSCC_Gen.Printer = Application.Printers(Me.cbPrintersList.ListIndex)
'MsgBox Report_Labels_SSCC_Gen.Printer.DeviceName
DoCmd.OpenReport Report_Labels_SSCC_Gen.Name, , , "Pre_SSCC BETWEEN '" & CStr(oldLastLabelRecordIndex) & "' AND '" & CStr(lastLabelRecordIndex) & "'", acHidden
DoCmd.Close acReport, Report_Labels_SSCC_Gen.Name, acSaveNo
Can anyone explain to me what am I missing or doing wrong?
As a reference, here's what's happening before and after the printer is set to the report.printer property:
Before setting the printer
After setting the printer
You can clearly see from the debug that the report has its printer property set to the printer I've chosen from the combobox.
However, for some reason I cannot understand, right after that line of code, when running the OpenReport to print the labels, it prints to zebra-01 printer instead...
Personally, I use the following code to print reports to a specified printer:
DoCmd.OpenReport "SomeReport", acViewPreview
Set Reports("SomeReport").Printer = Application.Printers("SomePrinter")
DoCmd.SelectObject acReport, "SomeReport"
DoCmd.PrintOut
DoCmd.Close
This only works with reports that are not printing to the default printer, so first open up the report in design view, go to page setup, and choose Use specific printer, then pick a printer (any printer), to make sure the report won't be printed on the system default printer.
If you want to specify paper size and bin, you can do so after setting the report printer:
DoCmd.OpenReport "SomeReport", acViewPreview
Set Reports("SomeReport").Printer = Application.Printers("SomePrinter")
Reports("SomeReport").Printer.PaperSize = 1
Reports("SomeReport").Printer.PaperBin = 2
DoCmd.SelectObject acReport, "SomeReport"
DoCmd.PrintOut
DoCmd.Close
Getting the right numbers for the paper and bin numbers is a bit complicated, however. The process is outlined here: https://learn.microsoft.com/en-us/office/vba/access/concepts/printing/programmatically-retrieve-printer-capabilities

Docmd.OpenReport showing first record but not rest in a record set

I'm using the code below to go thru a recordset and send individual reports to a person. Everything is working but the preview on the openreport on all but the first report are blank. Trying to figure out why if it sends the correct report to the person. It acts like it's opening a report and shows it then closes it but there's nothing but a blank page. Any thoughts would be appreciated!
Private Sub Command0_Click()
Dim daDb As DAO.Database
Dim daRs As DAO.Recordset
Dim sSql As String
sSql = "SELECT * FROM EmailedContributions;"
Set daDb = CurrentDb
Set daRs = daDb.OpenRecordset(sSql, dbOpenSnapshot)
Do Until daRs.EOF
Debug.Print daRs!MemberID
Debug.Print daRs!EmailName
DoCmd.OpenReport "Copy Of IRS Contribution Letter", acViewPreview, , "MemberID = " & daRs!MemberID, acWindowNormal
DoCmd.SendObject acSendReport, "Copy Of IRS Contribution Letter", acFormatPDF, daRs!EmailName, , , "IRS Contributions", "Attached are your contributions", False
DoCmd.Close acReport, "Copy Of IRS Contribution Letter"
Debug.Print daRs!EmailName
daRs.MoveNext
Loop
daRs.Close
Set daRs = Nothing
Set daDb = Nothing
End Sub

Programming MS Access report to filter on specific ID

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

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)

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.