Pass paramaters from one report to another in Access VBA - ms-access

I've been stuck with this issue for quite a while so help will really be appreciated...
I have a report based on a query that shows machine utilization for a list of machines. Before loading, the report prompts dialog boxes to enter the parameters for the query: sDate and eDate (start & end dates respectively).
Each record in that report has a command button that opens another report that specifies machine errors for the single machine selected.
The new report is based on a query that receives the parameters sDate, eDate and mCode (dates and machine code).
I'm trying to send the parameters from the first report to the second one so that when I open the new report, I won't have to enter anything.
I've tried different methods to send the paramaters by editing the command button's click event in vba.
startdate enddate, machinecode are invisible textbox fields in the first report with the values I need.
DoCmd.OpenReport "rpt_MachineBreaks", acViewReport, , "sDate=" & Me.startdate &
" AND eDate=" & Me.enddate & " AND mCode=" & Me.machinecode
But the dialog boxes prompt me to enter sDate, eDate and mCode
Another approach was to modify the query parameters for the new report using QueryDefs
Dim db As Database
Dim qry As QueryDef
Set db = CurrentDb
Set qry = db.QueryDefs("qry_singleMachineBreaks")
qry.Parameters("sDate") = Me.startdate
qry.Parameters("eDate") = Me.enddate
qry.Parameters("mCode") = Me.machinecode
DoCmd.OpenReport "rpt_singleMachineBreaks", acViewReport
Again, the dialog boxes prompt to enter sDate, eDate and mCode...
Help Please!!!

A common solution in Access for sharing parameters is to use a form. This allows you control of user input and can even be hidden, once the correct parameters are obtained. It is not difficult to refer to a form in a report or query:
SELECT Field1, Field2, ADate
FROM ATable
WHERE ADate = Forms!AForm!txtDate

You could remove the parameters from your underlying queries, and have your criteria defined in the Where clause of the DoCmd.OpenReport.
Another solutions is to use the OpenArgs param of DoCmd.OpenReport, and retrive that value in the OnOpen event of the report, using Me.OpenArgs.

Related

MS Access 2016: Set Report's RecordSource to get data from a Subform

Is there some sort of work-around that could make this possible? Or could anyone offer just some general advice on my situation below? I tried to set the record source through VBA but had no luck.
My situation:
I have a main form with a subform contained within, and I want the subform to be purely for data entry (Data Entry = Yes). Upon clicking a button, the user is sent from the main form to a report (print preview only). I want the source for this report to be the subform the users are entering data into, but I don't have this option from the report's property sheet itself (no forms), and I also was unable to set it through VBA. Here's my code, it's one line so I highly doubt it's the problem.
Private Sub Report_Load()
Reports![P18003 SDR Report].RecordSource = "P18003 SDR Subform"
End Sub
Previously, to work-around this I had a parameter query that waited for the user to enter data into an unbound textbox from the main form, and an after update trigger on that textbox would load any data relevant to that parameter (my employer and I miscommunicated the requirements).
It turns out though that I don't need to load any older data, and I run into problems with my current parameter query in the event that the user does input a parameter which loads old data - that old data is transferred to the report in addition to the new data they've just entered. This is the main problem with the method I am currently using, and it trashes almost all functionality with this form and report. The events that a user would need to enter a parameter which queries older data are few and far between, but it's not a functional product unless I can get the subform to be connected to the report directly. There's likely something obvious I'm missing here (or at least, I hope there is).
Thanks in advance for taking the time to read this and for any help you may offer.
you can either send the recordsource to the report itself in the OpenArgs by the open report event, after the click event in the subform
Private Sub btnSubform_Click()
Dim strSQL as String
strSQL = "SELECT * FROM SubformQuery WHERE ID = " & CurrentSubfromRecordID
Docmd.OpenReport, acViewReport, , , , strSQL
End Sub
and then in the Report.
Private Sub Report_Open(Cancel As Integer)
Me.recordsource = Me.OpenArgs
End Sub
Or you can make a paramter Query and set this Query criteria as record source for the report. So the parameter in the query is pointing to the current selected row in the subform. Like this:
--- At the Criteria in the Query designer:
--- RecordSource for the Report:
Forms![FormMain]![YourSubform]![ID]
Now every time the reports obens he gets the ID from the current selected record of your subform.

pass parameters to record source with query Access2007

I am relatively new to access and I have been tasked to improve the navigation of the app.
I have a form which is used to open the report.
The record source of the report is as follows,
SELECT
Projects.Project_Number,
Projects.Customer,
Projects.End_User,
Projects.Engineering_Company,
[Merged Ship and Delivery Dates].Sched_Next_Delivery_Date,
[Merged Ship and Delivery Dates].Sched_Next_Ship_Date,
Projects.QC_Pack_Req,
Projects.Target_QC_Pack_Date,
Projects.Invoice_QC_Pack
FROM
Projects LEFT JOIN [Merged Ship and Delivery Dates]
ON Projects.Project_Number = [Merged Ship and Delivery Dates].Project_Number
WHERE
(((Projects.Project_Number = [Project Number] )))
ORDER BY Projects.Project_Number;
I am trying to get the report to open up without prompting me every time. There are instances where I need to refresh the report or open it from other forms.
I have tried to use
DoCmd.OpenReport "Project Control Sheet", _
acViewReport, , _
"[Project_Number]=" & Me.ProjectNumber, , _
"[Project_Number]=" & Me.ProjectNumber
It is still unable to pass the parameters to the record source. Is there anyway for me to pass the parameters to the recordsource(query)?
I have tried to use
Forms![formName]ProjectNumber
in the where statement but this only works for a single form and I have other forms which opens up this report.
The purpose of refreshing the form is to allow users to view the changes made to the report after they have updated it.
If you remove the WHERE clause from the report's Record Source query, you can later filter the rows it returns with the WhereCondition option of the DoCmd.OpenReport method.
Dim strWhereCondition As String
strWhereCondition = "[Project_Number]=" & Me.ProjectNumber.Value
Debug.Print strWhereCondition ' <- view this in Immediate window; Ctrl+g will take you there
'DoCmd.OpenReport "Project Control Sheet", acViewReport, , strWhereCondition
DoCmd.OpenReport ReportName:="Project Control Sheet", _
View:=acViewReport, WhereCondition:=strWhereCondition
If you want a different approach, you could use a TempVar, since your Access version is 2007.
TempVars.Add "ProjectNumber", Me.ProjectNumber.Value
And change the Record Source query to use the TempVar ...
WHERE Projects.Project_Number = [TempVars]![ProjectNumber]

Drop Down list in Access Report

I have an access 2010 report that pulls from a query. The query has a Date, Name, and ID. What I'd like is a drop down box at the top of the report that filters on Date. So when a user selects a date, the report would refresh and show the results form the query for that date only. I can't seem to get this to work and need some direction.
Thanks in Advance!
You can open a report with arguments.
DoCmd.OpenReport ReportName, View, FilterName, WhereCondition, _
WindowMode, OpenArgs
( http://msdn.microsoft.com/en-us/library/office/bb238032(v=office.12).aspx )
This means that you can create a form using the MS Access form wizards and either add a combobox that shows all available dates, or just a textbox formatted to accept dates and use that as the basis of a where statement. Add a button to run the report and set the click event to something like:
DoCmd.OpenReport "ReportName", acViewPreview, , _
"MyDate=#" & Format(Me.txtDate,"yyyy/mm/dd") & "#"

Access Report not Filtering when Others Are

I have a form which allows the user to edit the properties of a filter via some combo boxes, then open a report. The report is opened with
DoCmd.OpenReport rptName, acViewReport, , whereClause, acWindowNormal
'whereClause = "Building = '005'" for instance
Some reports open fine, by which I mean they populate with the filtered info. Others, however, even though they are based off the same in-house template, IGNORE the filter all together and display a report based on ALL data (not the filtered data).
Why would a report ignore the filter? When I edit the reports in design mode after opening them with the form:
Working Report | Non Working Report
Filter: Building = '005' | Filter:
Filter On Load: No | Filter On Load: No
What could be causing the non-working report to not register the filter argument? There's no On Load VBA, nor any VBA, in these reports (except for an Export to PDF and a close button which is copy-paste for each report).
EDIT
Should have checked before, this happens regardless of whether or not the query driving the report is empty (ie the filter is never applied to some reports, regardless of blankness)
Not sure if the code will help, but:
Private Sub btnOpenSummary_Click()
If IsNull(Me.cboSummary) Then
MsgBox "Please select a building for the SUMMARY report."
Exit Sub
End If
strCrit = "Building = '" & Me.cboSummary & "'"
MsgBox strCrit
survArray = getSurveyArray()
For Each Survey In survArray
DoCmd.OpenReport Survey, acViewReport, , strCrit, acWindowNormal
Next Survey
DoCmd.OpenReport "Total Summary", acViewReport, , , , Me.cboSummary
End Sub
My fault.. there was code which had for some reason been linefed all the way down the code page and out of view. There was an On Open which played with the Control Source. It ended up being useless (as the control source only needed to be set once, not every time) but it was disabling the filter for some reason. Anybody else who may have this problem:
Make sure the control source is not being altered in your VBA for the report.
Thanks to those that helped, sorry my information was wrong.
My OnOpen code:
Private Sub Form_Open(Cancel as Integer)
Me.RecordSource = Me.Name
End Sub
It takes the name of the report, which corresponds to a name of a query, and puts it as the recordsource. (I have about 40 reports done this way, so it's dependent on names to make it fast to duplicate for different items).
Removing this made it work perfectly using Access 2010. Not sure if this was a problem specific to my setup or what, but, this change directly fixed it.
This is not a direct solution, but rather a workaround which should almost certainly work. Instead of applying filtering to the report, dynamically change the report data source by passing the where clause as a parameter.
To open the report use:
DoCmd.OpenReport rptName, acViewReport, , , acWindowNormal, whereClause
Note that the whereClause string is being passed as the OpenArgs parameter.
Then in the report VB:
Private Sub Report_Open(Cancel As Integer)
On Error GoTo ReportOpenError
If Not(IsNull(Me.OpenArgs)) Then
Me.RecordSource = Replace(Me.RecordSource,";"," WHERE " & Me.OpenArgs & ";")
End If
Exit Sub
ReportOpenError:
MsgBox "Unable to open the specified report"
Cancel = 1
End Sub
This solution assumes the report RecordSource is defined as a semicolon terminated SQL query (not a query name) and the record source does not already contain any WHERE, GROUP BY, etc., clauses. In those cases, it may be easier to redefine the query from scratch.
This problem may also occur when a report is copied and re-purposed. I had a report that was working fine then made a copy of it and was no longer able to filter it.
Perhaps there is a glitch in Access that causes it to ignore the filter when the report is copied under certain circumstances.
Solution: Instead of copying and re-naming the report, try creating a new report, linking the data source, and copying the fields back into place. If you are dealing with a new report, try re-creating it.

Best way to prompt for report parameters in microsoft access

Lets say you are designing a sales report in microsoft access. You have 2 parameters: Startdate and EndDate.
I can think of 3 ways to prompt the end user for these parameters when the report is run.
Create a form with 2 Text Boxes and a button. The Button runs the report, and the report refers back to the form by name to get the start date and end date.
Create a form with 2 text boxes and a button. The button runs the report but sets the appropriate filter via the docmd.openreport command.
Base the report on a Query and define query parameters. Access will automatically prompt for those parameters one by one.
Which is the best way to go?
Which is best depends on a number of factors. First off, if you want to run the report without parameters, you don't want to define them in the recordsource of the report. This is also the problem with your first suggestion, which would tie the report to the form (from Access/Jet's point of view, there is little difference between a PARAMETER declared in the SQL of the recordsource and a form control reference; indeed, if you're doing it right, any time you use a form control reference, you will define it as a parameter!).
Of the three, the most flexible is your second suggestion, which means the report can be run without needing to open the form and without needing to supply the parameters at runtime.
You've left out one possibility that's somewhat in between the two, and that's to use the Form's OnOpen event to set the recordsource at runtime. To do that, you'd open the form where you're collecting your dates using the acDialog argument, hide the form after filling it out, and then write the recordsource on the fly. Something like this:
Private Sub Report_Open(Cancel As Integer)
Dim dteStart as Date
Dim dteEnd As Date
DoCmd.OpenForm "dlgGetDates", , , , , acDialog
If IsLoaded("dlgGetDates") Then
With Forms!dlgGetDates
dteStart = !StartDate
dteEnd = !EndDate
End With
Me.Recordsource = "SELECT * FROM MyTable WHERE DateField Between #" _
& dteStart & "# AND #" & dteEnd & "#;"
DoCmd.Close acForm, "dlgGetDates"
End If
End Sub
[Edit: IsLoaded() is a function provided by MS. It's so basic to all my Access coding I forget it's not a built-in function. The code:]
Function IsLoaded(ByVal strFormName As String) As Boolean
' Returns True if the specified form is open in Form view or Datasheet view.
Const conObjStateClosed = 0
Const conDesignView = 0
If SysCmd(acSysCmdGetObjectState, acForm, strFormName) <> conObjStateClosed Then
If Forms(strFormName).CurrentView <> conDesignView Then
IsLoaded = True
End If
End If
End Function
Now, there are certain advantages to this approach:
you can pre-fill the dates such that the user would have to click only OK.
you can re-use the form in multiple locations to collect date values for multiple forms, since the form doesn't care what report it's being used in.
However, there is no conditional way to choose whether to open the form or not.
Because of that, I often use a class module to store filtering criteria for reports, and then check if the relevant class module instance has filter values set at the time the OnOpen event fires. If the criteria are set, then I write the SQL for the recordsource on the fly, if they aren't set, I just use the default recordsource (and any filter passed in the OpenReport argument). In this setup, you would run the report only after you've collected the criteria and set up the class module instance. The advantage of this approach is that the report can be run in either of the two contexts, and none of the parts need to know anything about each other -- the report simply needs to understand the class module's interface.
I used to use the Docmd.Openreport Where clause, your option 2. But I've switched to using report filters in the reports Open event, your option 1, as it supports creating PDF files which the Where clause does not. See Microsoft Access Report Printing Criteria Selection Form at my website.
As far as the dates go in SQL strings I use the Format statement as at Return Dates in US #mm/dd/yyyy# format
Also your option three can be handled by putting in the following example in the criteria in the reports record source SQL query. Forms!Form_Name!Control_Name. This is generally simpler for folks who don't want to get into VBA.