tags:

views:

2237

answers:

2

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?

+4  A: 

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:

  1. you can pre-fill the dates such that the user would have to click only OK.

  2. 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.

David-W-Fenton
+1. Option #3 is bad for several reasons incl. inability to trap and deal with problem entries (such as 2nd date is earlier in time than 1st date, entry isn't a valid date, etc). Petty observation: you wouldn't need the date delimiters (#) in your recordsource string (unless your form has those boxes as strings, but that's not advised).
Smandoli
Additional comment on these dates: never feed unformatted dates directly into the SQL. If your locale doesn't use dates in the US format, then you're going to get some nasty surprises.I always use a DateToSQL() function that converts a given date into a canonical string that can be fed into raw SQL safely.
Renaud Bompuis
I get an error on the IsLoaded function...."Sub or function not defined"
Aheho
In regard to the date delimiters, they are mandatory for fields declared as data types. And, yes, I agree that if you are not in a US locale, you need to feed your SQL non-ambiguous date values. I assumed that anyone who is in a non-US locale would have encountered and solved that issue a long time ago, but it's certainly worth mentioning for the novice.
David-W-Fenton
@David W. Fenton: "date delimiters, they are mandatory for fields declared as data types" -- presumably you meant "declared as DATETIME" ...either way, you are wrong. I know you are keen on folk trying things out before posting so try this: SELECT * FROM MyTable WHERE MyDateTime > '1990-01-01 00:00:00';
onedaywhen
"Data type mismatch in criteria expression." I tried it with both the default "SQL89" mode and with "SQL92" and both return the same error. Perhaps you're not testing in the right context, which in this post is very clearly within Access (read the question again), not using DAO or ADO or ODBC to query data in a Jet/ACE data file. Did you try it in Access? It seems that you quite clearly did not.
David-W-Fenton
Touché :) I misread the context. It indeed does not work in the Access UI. Quick fix (which is probably best practise anyhow) is to cast to DATEIME i.e. MyDateTime > CDATE('1990-01-01 00:00:00'); -- this is superior because if your *are* using the Access UI and use # delimiters then your SQL code will secretly change the date literals to its own format (IIRC #m/d/yyyy#) and not respect the user's chosen format.
onedaywhen
Or use DateValue() or DateSerial(). Anyone who is not in a US locale should already know this, I think.
David-W-Fenton
Possibly but I find CDATE to be more portable e.g. when going Access database engine to SQL Server its a simple transform: CDATE('1990-01-01 00:00:00') -> CAST('1990-01-01T00:00:00' AS DATETIME);
onedaywhen
DateSerial() is certainly a different affair, but DateValue() is identical to CDate in terms of its arguments and output.
David-W-Fenton
@David W. Fenton: "DateValue() is identical to CDate in terms of its arguments and output" -- SQL code? incorrect. SELECT CDATE(32874) returns 1990-01-01 as a whereas SELECT DATEVALUE(32874) errors with data type mismatch. VBA? Take a look in the Obejct Browser: CDate() returns a Date whereas DateValue() returns a Variant. Ha! Two-one to me, your move ;)
onedaywhen
You've changed the rules of the game. You started with converting a string to a date, which is what DateValue() does. Now you're asking to convert an integer to a date. In Jet, Integers don't need to be converted, so CDate(32874) is a waste of time. DateValue() may return a variant, but it is of subtype Date, so I don't see the issue. Given that we're dealing with a context in which the Jet and Access expression services are operative, I don't think there's much of a problem there.
David-W-Fenton
"CDate(32874) is a waste of time" -- subjective. I'd have to think about and possibly experiment with how comparing an INTEGER to a DATETIME would work in practise e.g. would the both get promoted to FLAOT? So rather than do this I would cast anything that didn't derive from a DATETIME column or SQL PROCEDURE argument I would cast to DATETIME using CDATE because it is more consistent than the alternatives, DateValue included. In this scenario, using CDATE saves me time. Yes, I know: subjective.
onedaywhen
The Jet/ACE datetime data type and the VBA datetime data type are both composed of an integer part (which is the date) and a decimal part (the time). Thus, in the context we were discussing, there is nothing to think about. CDate(32874) is not different than 32874 when using it with a datetime field or variable.
David-W-Fenton
CDate() saves time only if you don't know what the data type is of the field you're operating on. A field with integer values in it that can somehow be validly transformed into datetime values does not need conversion at all. Now, if you've got a field that mixes integer values and strings, you've got a field of type text, so DateValue() is going to work. I see no justification for preferring CDate() because there is no scenario where the fact that it can accept both numeric and string input is going to be of any actual use.
David-W-Fenton
IIRC the DATETIME data type is a FLOAT (Access UI = Double) with limits e.g. the maximum value is sightly larger than CDBL(#9999-12-31 23:59:59#) even though ACE/Jet's temporal functions don't support time granules smaller than one second. From a quick play it seems that data type precedence is INTEGER -> FLOAT -> DATETIME until it goes outside the valid DATETIME range then it goes back to FLOAT. DECIMAL is *always* of a higher precedence than DATETIME but only of higher precedence than FLOAT within the DECIMAL range. Why can the Access team document this stuff so we don't need to experiment?!
onedaywhen
...so operating on an INTEGER and DATETIME will always promote the INTEGER to either DATETIME or FLOAT depending on the value range e.g. SELECT TYPENAME(CDATE(32874) + CLNG(32874)), TYPENAME(CDATE(32874) + CLNG(3287400)) returns Date and Double respectively. Then there's CVDATE() which unlike the other cast functions can handle NULL... you say tomaydo, I say tomarto, let's call the whole thing off? :)
onedaywhen
I didn't understand a single line of the last two comments. ;)
David-W-Fenton
+1  A: 

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.

Tony Toews
While it's "simpler" to begin with, it makes things complicated once you need to use the report without the hardwired reference to the external form in its recordsource. I've seen lots of Access apps built with this "simpler" method where the same report layout is saved 8 or 10 times, with the only difference between them being the recordsource.
David-W-Fenton
No argument there. But the user doesn't have to learn VBA which can be an insurmountable task and exceedingly frustrating. Of course I expect anyone visiting StackOverflow should know enough to work with VBA a little bit.
Tony Toews