The code below generates PDF reports for supervisors who have employees expiring between StartDate and StopDate fields on a form. I am getting multiple reports for supervisors who do not have employees expiring in that range, blank reports essentially. The code also puts out the correct reports that have data.
How can I prevent OutputTo from saving the blank reports?
SQL for reference query (qry_Distinct_Supervisors):
PARAMETERS StartDate DateTime, StopDate DateTime;
SELECT DISTINCT qry_Base_For_All.Supervisor, qry_Base_For_All.LID, qry_Base_For_All._Status, qry_Base_For_All.LASTNAME, qry_Base_For_All.FIRSTNAME, qry_Base_For_All.[End Date]
FROM qry_Base_For_All
WHERE (((qry_Base_For_All.Supervisor) Is Not Null) AND ((qry_Base_For_All.LASTNAME) Is Not Null) AND ((qry_Base_For_All.[End Date]) Between [StartDate] And [StopDate]));
SQL for Report
SELECT DISTINCT qry_Base_For_All.L_ID, qry_Base_For_All.LASTNAME, qry_Base_For_All.FIRSTNAME, qry_Base_For_All.P_ID, qry_Base_For_All.Company, qry_Base_For_All.[End Date], qry_Base_For_All.Supervisor, qry_Base_For_All.Title
FROM qry_Base_For_All
WHERE (((qry_Base_For_All.[End Date]) Between [Forms]![frm_Bldg_Access]![StartDate] And [Forms]![frm_Bldg_Access]![StopDate]) AND ((qry_Base_For_All.Title) Like "*" & "outsource" & "*"));
VBA to save reports
Private Sub btn_Print_Report_Click()
'split report into PDFs named after supervisor and open a separate email with each report attached
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim MyFileName As String
Dim mypath As String
Dim temp As String
Dim qry As QueryDef
Dim StartDate As DAO.Parameter
Dim StopDate As DAO.Parameter
Set db = CurrentDb()
Set qry = db.QueryDefs("qry_Distinct_Supervisors")
mypath = "C:\Users\cw52450\Desktop\Test Exports\"
qry.Parameters("StartDate").Value = Forms!frm_Bldg_Access!StartDate
qry.Parameters("StopDate").Value = Forms!frm_Bldg_Access!StopDate
Set rs = qry.OpenRecordset(dbOpenSnapshot)
'populate rs
If Not (rs.EOF And rs.BOF) Then
rs.MoveLast
rs.MoveFirst
'start report generation loop
'Currenlty outputting blank reports as well as needed ones
Do While Not rs.EOF
temp = rs("Supervisor")
MyFileName = rs("Supervisor") & Format(Date, ", mmm yyyy") & ".PDF"
DoCmd.OpenReport "rpt_Expiring_Access", acViewReport, , "[Supervisor]='" & temp & "'"
DoCmd.OutputTo acOutputReport, "", acFormatPDF, mypath & MyFileName
DoCmd.Close acReport, "rpt_Expiring_Access"
DoEvents
rs.MoveNext
Loop
Else
MsgBox "There are no records in the recordset."
End If
MsgBox "Report generation complete."
Set rs = Nothing
Set db = Nothing
Set qry = Nothing
End Sub
Related
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 & "'"
I have some code that I copied and modified from Export Query in VBA loop to select data based on String Value
The code works although the problem is that when it runs it creates a query in the database which is then deleted at the end. If the code breaks half way through, this query is still in the database. So when the code is run again it gives an error message saying it can't create the query as it already exists.
The query that is created within the database is named "Select * from SalesData"
The objective is that I have a query called "SalesData" which includes sales information for a number of countries. I want to export all the data for each country into an Excel file in a loop without creating any additional Access objects. Is it possible to just filter the existing query within the VBA without creating the temporary object?
Can anyone suggest any modifications to the below code to achieve this?
Sub TEST()
Dim db As DAO.Database
Set db = CurrentDb()
Dim rs1 As DAO.Recordset
Set rs1 = db.OpenRecordset("Select Distinct Country From SalesData")
Dim v As String
Dim strQry As String
Dim qdfTemp As DAO.QueryDef
Dim strQDF As String
strQDF = "select * from SalesData"
Do While Not rs1.EOF
v = rs1.Fields(0).Value
strQry = "SELECT * FROM SalesData WHERE Country = '" & v & "'"
Set qdfTemp = CurrentDb.CreateQueryDef(strQDF, strQry)
qdfTemp.Close
Set qdfTemp = Nothing
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, _
strQDF, "C:\Users\me\Desktop\VBA_TEST\" & v & ".xlsx", True
CurrentDb.QueryDefs.Delete strQDF
rs1.MoveNext
Loop
rs1.Close
End Sub
As far as I'm aware, it would not be possible to use the TransferSpreadsheet method to extract a parameterised version of your SalesData query without either modifying the SQL of the SalesData query itself or using an additional query with selection criteria applied to the data returned by SalesData.
However, you needn't delete & recreate such query with every iteration of the loop - instead, simply modify the SQL property of the query, e.g.:
Sub test()
Dim qry As String: qry = "salesdata_temp"
Dim sql As String: sql = "select * from salesdata where country = '{0}'"
Dim out As String: out = "C:\Users\me\Desktop\VBA_TEST\"
Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
On Error Resume Next
DoCmd.DeleteObject acQuery, qry
On Error GoTo error_handler
Set dbs = CurrentDb
Set qdf = dbs.CreateQueryDef(qry, sql)
With dbs.OpenRecordset("select distinct country from salesdata")
If Not .EOF Then
.MoveFirst
Do Until .EOF
qdf.sql = Replace(sql, "{0}", !country)
DoCmd.TransferSpreadsheet acExport, , qry, out & !country & ".xlsx", True
.MoveNext
Loop
End If
.Close
End With
exit_sub:
On Error Resume Next
DoCmd.DeleteObject acQuery, qry
Exit Sub
error_handler:
MsgBox "Error " & Err.Number & ": " & Err.Description, vbExclamation + vbOKOnly, "Error"
Resume exit_sub
End Sub
Thanks to the input here, it seems that the only way to do it is to manipulate an existing query in the database or to create a query in the VBA script and then delete it at the end.
See below for an example of the first approach, the code uses a query already in the database called "blankquery".
Sub TEST()
Dim db As DAO.Database
Set db = CurrentDb()
Dim rs1 As DAO.Recordset
Set rs1 = db.OpenRecordset("Select Distinct Country From SalesData")
Dim qdfTemp As DAO.QueryDef
Dim v As String
Dim strQry As String
Dim strQDF As String
strQDF = "blankquery"
Do While Not rs1.EOF
v = rs1.Fields(0).Value
strQry = "SELECT * FROM SalesData WHERE Country = '" & v & "'"
db.QueryDefs(strQDF).sql = strQry
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, _
strQDF, "C:\Users\me\Desktop\VBA_TEST\" & v & ".xlsx", True
rs1.MoveNext
Loop
rs1.Close
End Sub
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)
Hi I have been trying this for hours and it doesn't matter how much I search to try different options I cannot get the lookup for give a result that I am looking for. I am testing it using a date and work code that I know is in the table that I am referring to.
I am using the input box to provide the date and fixing the work code as 13 (Dispatch). The lookup should be returning the date in the table as the date input is in the table. My code is:
Sub Append_Dispatch()
Dim dbs As Object
Dim qdf As querydef
Dim InputDateString As String
Dim InputDate As Date
Dim RtnDate As String
Dim chkDate As Date
Dim WC As Long
Set dbs = CurrentDb
Set qdf = dbs.querydefs("Dispatch Append to Production Data")
WC = 13
InputDateString = InputBox("Please enter start date to import", "Date")
InputDate = DateValue(InputDateString)
RtnDate = DLookup("[Date of Action]", "Production Data", "[Date of Action]= #" & InputDate & "# AND [Work Code] = " & WC & "")
chkDate = DateValue(RtnDate)
If InputDate = chkDate Then
IB = MsgBox("This dispatch date has already been entered:" & vbCrLf & "Please check and use a date after " & Dte, vbOKOnly, "Date Error")
Exit Sub
End If
'qdf.Parameters("Dispatch Date").Value = InputDate
'qdf.Execute
'qdf.Close
'Set qdf = Nothing
'Set dbs = Nothing
End Sub
Also I cannot get the code to work after the end if to input the parameter and run the append query. But that is another issue.
Any ideas please.....
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.