I have a large Access table. I have a query entitled qry_ExtractYear which I would like to have the criteria modified by the user and the the results exported. I have the code here which works but I am having the issue of being prompted repeatedly for sDate1 and sDate2 before the export occurs. What am I doing wrong please?
Sub ExportAnnualQuoteActivity()
Dim db As dao.Database
Set db = CurrentDb
Dim qdf As dao.QueryDef
Dim sDate1 As String
Dim sDate2 As String
sDate1 = InputBox(prompt:="Start Date YYYYMMDD")
sDate2 = InputBox(prompt:="End Date YYYYMMDD")
Set qdf = db.QueryDefs("Qry_ExtractYear")
qdf.SQL = "Select * From [tbl_QuoteData] WHERE [Quote Date] BETWEEN sDate1 AND sDate2"
DoCmd.Save acQuery, "Qry_ExtractYear"
DoCmd.OutputTo acOutputQuery, "Qry_ExtractYear", acFormatXLSX, "T:\Actuary\Metrics\NB\Data\Yearly\tbl_QuoteData_" & Left(sDate2, 4) & ".xlsx", True
End Sub
It's because the constructed SQL has literal text "sDate1 AND sDate2" and not the values of those variables. Concatenate variables and use date/time # delimiter.
WHERE [Quote Date] BETWEEN #" & sDate1 & "# AND #" & sDate2 & "#"
If field is text type, use apostrophe delimiter instead of #. Number fields do not require delimiters.
Advise not to use InputBox as cannot easily validate user input. Reference controls on form for variable user input.
Related
So I have this Access form where I use this VBA code with a DAO connection to a MySQL database. Everything works great but if the user closes the form without clicking save button the new record is saved anyway.
So what I'm looking for is if there's any way the on the on close event I can stop the new record being saved to the database?
The code I have,
Private Sub Form_Load()
'Set Form Recordset
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim SQL As String
Set db = OpenDatabase("", False, False, Globales.ConnString)
SQL = "SELECT tbl6Suplidores.ID, tbl6Suplidores.NombreSuplidor, tbl6Suplidores.NumeroComerciante, tbl6Suplidores.DescripcionBienes, tbl6Suplidores.NombreContacto, tbl6Suplidores.NumeroTelefono, tbl6Suplidores.Email " _
& "FROM tbl6Suplidores;"
Set rs = db.OpenRecordset(SQL, dbOpenDynaset, dbAppendOnly)
Set Me.Form.Recordset = rs
End Sub
I'm thinking that since I used the dbAppendOnly it won't let me just delete current record on close event?
Any ideas welcome!
Thanks!
Consider a different approach where you have users enter an unbound form and click a save button to update the MySQL table from populated fields. Exiting form without save will do nothing. This is also a more proactive approach as it allows you to check validation and other logic prior to running save action.
Below uses a parameterized append query with QueryDefs. Also, ID is assumed to be an autonumber and hence left out of query. Sub should be placed behind the OnClick trigger event of save button.
Private Sub SaveButton_Click()
Dim db As DAO.Database, qdef As DAO.QueryDef
Dim SQL As String
Set db = OpenDatabase("", False, False, Globales.ConnString)
' PREPARED STATEMENT WITH NAMED PARAMETERS
SQL = "PARAMETERS ns_param VARCHAR(255), ncom_param INTEGER, db_param VARCHAR(255), " _
& " ncnt_param INTEGER, nt_param INTEGER, e_param VARCHAR(255);" _
& " INSERT INTO (NombreSuplidor, NumeroComerciante, DescripcionBienes, " _
& " NombreContacto, NumeroTelefono, Email) " _
& " VALUES (ns_param, ncom_param, db_param, ncnt_param, nt_param, e_param);"
' INITIALIZE QUERYDEF
Set qdef = db.CreateQueryDef("", SQL)
' BIND PARAMETERS TO FORM FIELDS
qdef!ns_param = Forms!MyFormName!NombreSuplidor
qdef!ncom_param = Forms!MyFormName!NumeroComerciante
qdef!db_param = Forms!MyFormName!DescripcionBienes
qdef!ncnt_param = Forms!MyFormName!NombreContacto
qdef!nt_biens_param = Forms!MyFormName!NumeroTelefono
qdef!e_param = Forms!MyFormName!Email
' RUN ACTION QUERY
qdef.Execute dbFailOnError
Set qdef = Nothing
End Sub
I'm new on the MS Access, now I have a report based on the table with 100 records. I want to output the pdf files based on each record. It means each record will have its own single pdf file and the file name will be based on the record's column name.
I have searched on the Internet and I found this vba code is work.
Option Compare Database
Option Explicit
Private Sub Command4_Click()
Dim rsGroup As DAO.Recordset
Dim ColumnName As String, myPath As String
myPath = "C:\test\"
Set rsGroup = CurrentDb.OpenRecordset("SELECT DISTINCT columnName FROM Table_Name", _
dbOpenDynaset)
Do While Not rsGroup.EOF
ColumnName = rsGroup!columnName
' OPEN REPORT, FILTERING RECORDSOURCE BY COLUMN VALUE
DoCmd.OpenReport "Table_Name_Report", acViewPreview, , "Column='" & ColumnName & "'"
' OUTPUT REPORT TO FILE
DoCmd.OutputTo acOutputReport, "Table_Name_Report", acFormatPDF, _
myPath & ColumnName & ".pdf", False
' CLOSE PREVIEW
DoCmd.Close acReport, "Table_Name_Report"
rsGroup.MoveNext
Loop
rsGroup.Close
I never used VBA, and every time I run this code, it will return a window and let me input the column record value. That's not automatically, how to change the code to let it read the record value automatically and populate the pdf?
The way I would do this is to just dynamically set the query the report is based on (i.e. the recordsource) complete with the "columnName". Something like:
(code not run)
Public Sub cmdOpenMyReport_Click()
Dim strSQL As String
Dim rsGroup As DAO.Recordset
Dim ColumnName As String, myPath As String
myPath = "C:\test\"
Set rsGroup = CurrentDb.OpenRecordset("SELECT DISTINCT pharmacyName FROM Sfwy_Patients_New", dbOpenDynaset)
Do Until rsGroup.EOF
ColumnName = rsGroup!pharmacyName
strSQL = "SELECT ... WHERE Column = " & COLUMName & ";" 'copy sql from the report record source and put in the column name as a variable
CurrentDb.QueryDefs("myReportRecordSource").SQL = strSQL
' OUTPUT REPORT TO FILE
DoCmd.OutputTo acOutputReport, "Sfwy_Patients_New_Report", acFormatPDF, _
myPath & ColumnName & ".pdf", False
rsGroup.movenext
Loop
end sub
Let's say I have an hundred page report in Access 2010 that includes lists of names (with some other details), grouped by a variable called NOM_RITIRO.
I would like to output the report into different PDF files, one for each value of the variable used for grouping.
I was trying to figure out how to make this code work:
Sub SplitPdf()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim Source As String
Dim SQL As String
Dim MyPath As String
Dim MyFilename As String
MyPath = "D:\Folder\"
Set db = CurrentDb
SQL = "Select NOM_RITIRO From QueryNominativi Group By NOM_RITIRO"
Set rs = db.OpenRecordset(SQL)
While Not rs.EOF
MyFilename = "TK_" & rs!NOM_RITIRO & ".pdf"
' Apply quotes as NOM_RITIRO is a string.
DoCmd.OpenReport "ElenchiNominativi", acViewPreview, , "NOM_RITIRO = '" & rs!NOM_RITIRO.Value & "'"
DoCmd.OutputTo acOutputReport, , acFormatPDF, MyPath & MyFilename, False
DoCmd.Close acReport, "ElenchiNominativi"
rs.MoveNext
Wend
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub
I got stuck when I try to run the DoCmd.OpenReport.
I get the message box "Enter parameter Value" like if the recordset is not passing any data
Any idea of what I did wrong?
If NOM_RITIRO is not a field in the recordsource of your report called "ElenchiNominativi" (or mis-spelled) then it will prompt you to enter a parameter value.
Similarly, if the recordsource of your report is a query that contains a fieldname not referenced in any of the tables, you will also get this prompt.
I am trying to add a received date to my table for all the files imported. We receive files and process them up to a week later. I have my import set up and everything but I added a column called "Receive Date". I also added a Date Picker and have it setup in VBA to grab it. I am not sure how to change ALL the records in the table to be the date selected.
Private Sub Command2_Click()
Dim Rec As String
Rec = Text0
End Sub
As you can tell I am just starting this but I do not know which direction I should be going from here. I would assume call the record set and table but I am unsure. Any assistance would be greatly appreciated. Thanks in advance
Sounds like you want the [Receive Date] in all rows of your table set to the date value selected in your Text0 text box. If that is correct, you can execute a SQL UPDATE statement from Command2_Click().
Private Sub Command2_Click()
Dim strUpdate As String
Dim db As DAO.database
Dim qdf As DAO.QueryDef
strUpdate = "PARAMETERS which_date DateTime;" & vbCrLf & _
"UPDATE YourTable" & vbCrLf & _
"Set [Receive Date] = which_date;"
Debug.Print strUpdate
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", strUpdate)
qdf.Parameters("which_date") = Me.Text0
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing
End Sub
I have a form (Cobind_frmMain) that allows the user to create a pool of titles that are attached to it. So there is a top level Pool Name (TopLvlPoolName) and on a subform, the titles are added to it. What I need is to issue a Report for each of the titles. I have the report and queries all set up. Right now, the report will show all the titles in one file. The titles are in a field called "CatCode".
What I need is the following:
1. Save each title as a PDF and save it to our server.
2. Open email and attach the PDF.
3. Repeat until all titles are done.
EDIT: This is what I have so far for code and the error message I still get is: "Too Few Parameters" on the Set Recordset line. I'm trying to set the parameter in the strSQL line. I want the PartPoolName (in Cobind_qryReport, a query) to equal the TopLvlPoolName on the open form. The SQL for Cobind_qryReport is listed below:
Private Sub btn_Run_Click()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strSQL As String
Set db = CurrentDb
strSQL = "Select * FROM Cobind_qryReport WHERE PartPoolName = " & Me.TopLvlPoolName
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 Recordset.EOF = False
DoCmd.OutputTo acOutputReport, "Cobind_rptMain", acFormatPDF, "K:\OB MS Admin\Postage\CoBind Opportunities\Sent Invites\" & [CatCode] & "_" & [PartPoolName] & "Cobind Invite_" & Format(Now(), "mmddyy") & ".pdf"
DoCmd.SendObject acSendReport, "Cobind_rptMain", acFormatPDF, , , , [CatCode] & "_" & [PartPoolName] & " Cobind Invite", "Please find the cobind invite attached. Response is needed by " & [RSVP] & ". Thank you.", True
Recordset.MoveNext
Loop
End If
Exit_PO_Click:
MsgBox ("It didn't work")
Exit Sub
Err_PO_Click:
MsgBox Err.Description
Resume Exit_PO_Click
End Sub
Cobind_qryReport SQL:
SELECT tblEvents.EventTitle, Cobind_tblPartic.CatCode, Cobind_tblPartic.CodeQty, Cobind_tblPartic.PartPoolName, Cobind_tblTopLvl.RSVP, Cobind_tblPartic.ID
FROM Cobind_tblTopLvl, Cobind_tblPartic INNER JOIN tblEvents ON Cobind_tblPartic.CatCode = tblEvents.EventCode
GROUP BY tblEvents.EventTitle, Cobind_tblPartic.CatCode, Cobind_tblPartic.CodeQty, Cobind_tblPartic.PartPoolName, Cobind_tblTopLvl.RSVP, Cobind_tblPartic.ID
ORDER BY Cobind_tblPartic.ID;
Thank you again for all your help!
You're query Cobind_qryReport has a parameter that you need to set. if you want to know the parameter name try the following code
Dim qdf As QueryDef
Set qdf = CurrentDb.QueryDefs("Cobind_qryReport")
If qdf.Parameters.Count > 0 Then
MsgBox (qdf.Parameters(0).Name)
End If
Update
Since you know you've got a parameter doing select * from Cobind_qryReport it might just be easier to set the parameter and then use the qdf to open the recordset e.g.
Dim rs as DAO.Recordset
Dim qdf As QueryDef
Set qdf = CurrentDb.QueryDefs("Cobind_qryReport")
qdf.Parameters(0).Value = 7832
Set foo = qdf.OpenRecordset()
Note: you can use the parameter name in the place of the ordinal when setting the parametervalue
e.g. qdf.Parameters("Foo").value = 7832