Wednesday, June 29, 2011

Crystal Reports : Automatically derive dates based on "Last Week"

This is a nice trick for those of you that want to cut down on parameter input for your end users.

Suppose a report needs to only print records with dates from last Monday through Friday. You could of course provide a date range parameter and let the user choose for each printing of the report.

You could however, use the nifty LastFullWeek function in crystal to return these values automatically.

The first thing to keep in mind here is that LastFullWeek will actually return a Date Range, NOT a Date Value. In order to see what dates LastFullWeek is actually returning, we will need to create two formula fields. {@DateStart} and {@DateEnd}.

The code for {@DateStart} : MINIMUM(LastFullWeek)
The code for {@DateEnd} : MAXIUMUM(LastFullWeek)

Drag those two fields onto your report. You'll see that in the Crystal Universe, the LastFullWeek starts on a SUNDAY and ends on a SATURDAY. So if we just want Monday through Friday, we need to do some tweaking.

The code for {@DateStart} : MINIMUM(LastFullWeek) + 1
The code for {@DateEnd} : MAXIUMUM(LastFullWeek) - 1

Now the formulas are returning Monday to Friday and we can use them in our Selection Criteria thusly (assuming we are looking at a field called {HISTORY.ONDATE})

{HISTORY.ONDATE} IN {@DateStart} TO {@DateEnd}.

Try it!