You are on page 1of 16

CR.

NET Book by Bischof- Chapter 7 - Copyright 2003

Page 1 of 16

Formulas enable you to analyze the data in your report as it is being printed. There are two
circumstances when you need to use formulas. The first circumstance is when you need to show the
results of calculations based off the raw data being printed. For example, when printing the monthly
sales volume for a product you can calculate the percent of total sales. Storing this in the database isnt
practical because it is more efficient to calculate that value on an as needed basis rather than waste space
storing the number in the database. The second circumstance that formulas are needed is when you want
to dynamically modify the formatting of fields or sections on the report as it is printing. For example,
you can simulate a green bar report by using a formula that changes the format of every other row to
show a shaded background. Youll soon see that the flexibility and power of functions make them one of
the most useful features of Crystal Reports.
This chapter is the first of three that show you how to use formulas to make your reports vibrant. It
shows you when and how to write formulas using the Formula Editor. The next chapter is a Basic syntax
primer so that you know how to use Basic syntax, one of the formula languages used by Crystal Reports.
Chapter 9 is a reference for the common functions that are built into Crystal Reports.
Throughout this chapter, the examples use the built-in programming language, Basic syntax. The
syntax rules of this language and its built-in functions are covered in the next two chapters. Although
this language isnt covered in this chapter, it is very much like VB .NET and you shouldnt have any
problem understanding the examples here. In fact, the two languages are so similar that you might be
tempted to skip over the next two chapters because you already know how to program in VB .NET. I
dont recommend this because Basic syntax has been designed to make reporting easier, and it adds a lot
of new functionality not found in VB .NET. Learning about this new functionality can show you how to
simplify some reporting specific tasks would be more difficult that in VB .NET.
Crystal syntax is the default language for the formula editor. You will find yourself changing this to
Basic syntax everytime you open the formula editor. To make Basic syntax the default language, rightclick anywhere on the report designer and select Designer/Default Settings. On the Reporting tab, there
is a drop-down box at the bottom that sets the default language. Change it to Basic syntax.

The Formula Editor shown in Figure 7-1 is where you create and edit formulas. It consists of four
separate windows. The three windows along the top of the window present the entire set of tools to write
a formula. Within these three windows is every available field, syntax construct, and built-in formula.
The bottom window is the formula window where you write and edit the formula.

http://www.WillyDev.Net

CR.NET Book by Bischof- Chapter 7 - Copyright 2003

Page 2 of 16

Figure 7-1. The Formula Editor window.


The top three windows are designed so that if you double-click any of the items in one of the trees,
that item will appear in the code window at the current cursor position. You can also drag and drop the
item into the code window. Effectively, you could write most of you formulas without doing any typing.
Just double click the appropriate items in the tree and let the formula be built for you. Personally, as a
programmer I dont find this very practical. Scrolling through a hierarchy of syntax trees isnt nearly as
efficient as just typing it all in myself. However, it is very useful to have these trees available because
they are almost like having a min-help file available. If there is a built-in function that you havent used
in a while, then you can always browse through the tree structure to look for it. You can also look at it
just to find out all the different functionality that is available to you.
In the top right corner is the drop-down list for whether you want to use Crystal syntax or Basic
syntax. By default, Crystal Reports sets it to be Crystal syntax. This list is discussed in more detail in the
Chapter 5, but the following are brief definitions.

The Field Tree shows all the fields on the report. This ranges from formulas to groups
to data fields. Below that it shows every field in the current data source (whether they
are in the report or not). You can use any report field in your formula as well as any

http://www.WillyDev.Net

CR.NET Book by Bischof- Chapter 7 - Copyright 2003

Page 3 of 16

database field. The database field doesnt need to be displayed on the report for it to be
used in a formula.

The Function Tree is the middle window. It shows all the functions that are available.
At first, this tree is a nice crutch to lean on as you learn the Basic syntax language. You
will find that since Basic syntax is so similar to VB.NET you will quickly learn the
language and stop using the Function Tree as much.

The Operator Tree is similar to the Function Tree whereas it starts out as a nice crutch,
but you will quickly outgrow it and know most of the operators by heart.

The Formula window is where you write the formulas. The font is color-coded so that
reserved words use a blue font. Comments are in green. Variables and value constants
are in black.

As you write formulas, you need to save and check the syntax of the formula. The left most portion of
the toolbar has buttons that provide this functionality. Figure 7-2 shows that portion of the toolbar.

Figure 7-2. Formula buttons.


The buttons shown in Figure 7-2 are described here:

A blank sheet, the first button, is used for creating a new formula. It first saves the
current one and checks its syntax.

A disk, the second button, saves the formula and checks the syntax. You can continue
working on the existing formula.

A disk with an x, the third button, a disk with an x, checks the syntax and closes
the Formula Editor. You will probably use this one most of the time.

The formula icon with a checkmark, the fourth button, checks the syntax of the
formula. It gives you a message box telling you whether it is okay and then lets you go
back to working on the formula. You use this when you just typed in a statement and
you arent certain if you got it exactly right or not.

The drop down list shows all the available formulas. Use this when you are done
working on the current formula and you want to edit another formula. This can only be
used with existing formulas, not creating new ones.

Whenever you save a formula, the syntax is always verified first. This insures that if there is
something wrong with your formula, then you can correct right away. When a syntax error is found, a
message box appears informing you of the problem. Unfortunately, the error messages that appear are
usually not very helpful for telling you what is wrong with the formula. You frequently have to decipher
this yourself. If you find that there is a syntax error in your formula, you are not required to fix it right
away. You can save it as is, and then come back later to fix the errors. Just dont forget to fix it or else

http://www.WillyDev.Net

CR.NET Book by Bischof- Chapter 7 - Copyright 2003

Page 4 of 16

your report wont run properly.

A report gets the majority of its data from a data source. This could be a table in a database or an XML
data feed. Due to space considerations, the data normally only has raw data in it. It doesnt waste
resources by saving data that can be derived by other means (e.g. calculations). That is the responsibility
of the data consumer that is reading the data. As far as this book is concerned, the data consumer in
question is your report. It is responsible for taking the raw data and performing any necessary
calculations that are needed on the report. The calculation can be used internally and later called by
other formulas or they can be displayed directly on the report. For example, you can have a formula that
uses the number of items ordered to calculate the percent discount that was given to the customer and
display it.
Crystal Reports has two ways of adding and editing formulas. The first way is via the report
designer. Within the Field Explorer window, right click on any of the formula fields and select Edit or
New. You can also right click on the Formula Fields tree node. The Field Explorer window is shown in
Figure 7-3.

Figure 7-3. The field explorer window.


Once youve added a formula to the Field Explorer, you can display it on your report by dragging
and dropping it to the report. You can tell the difference between fields that are from a database versus
fields that are from formulas because the formula fields are prefixed with an @. You can also edit these
fields by right clicking on them within the report layout and selecting Edit.
Adding a new formula or editing an existing formula brings up the Formula Editor that is discussed
in the first section of this chapter.

Reports by their very nature are somewhat static. Although the printed data changes and the totals are

http://www.WillyDev.Net

CR.NET Book by Bischof- Chapter 7 - Copyright 2003

Page 5 of 16

different every time, the basic format of the report stays the same. For example, if the first field in a
column has a font of Arial and is black, then you can assume that every field in that column is also
going to have a font of Arial and will be black. And that is how it should be. After all, if every field in a
column had a different font, it would be very hard to read and people would question the abilities of the
report designer. But wouldnt it be nice to be viewing a report and immediately notice that a certain
quantity of inventory is below the minimum and that it needs to be reordered? You can do this by
changing its font to bold or making it red. There might even be a special note to the side of the report
telling you whom to notify. In this circumstance, making a report dynamic increases its usefulness to the
reader without adding clutter.
Crystal Reports provides you with a variety of ways to make a report dynamic. It gives you the
ability to use formulas that dynamically modify the visual properties of fields and sections on a report.
For example, you can use a formula that returns either True or False with the Suppress property of a
section to either show or hide a section. You could also use a formula that returns a string and this can
be used to add a special message at the end of each row.

Adding Formulas
When you modify a property in the designer, the changes you make to that property will stay the
same throughout the report run. Many properties, but not all, can have a formula attached to them so that
their value can be modified based upon other fields in the report. Clicking on the formula button next to
a property lets you insert a formula to do this. The formula button is shown in Figure 7-4. It has a blue
X-2 and there is a horizontal pencil underneath it. Once you add a formula to a property the X-2
turns red and the pencil is at an angle. This is shown in Figure 7-5. If a property doesnt have a formula
button next to it then you cant associate a formula with it.
Figure 7-4. A button with no formula associated with it.
Figure 7-5. A button with a formula associated with it.
When adding a formula to a property, you have to determine the data type that the property uses.
This can be anything from Boolean or pre-defined constants to simple values such as a string or a
number. The formula must return the proper data type to the property. If you try to return the wrong data
type, the Formula Editor will return an error when you try to save it.
Figure 7-6 shows the Section Editor dialog box. All the properties displayed here use checkboxes.
These properties are either on or off. Formulas that are associated with these properties have to return
True or False. As expected, returning True is same as a checked box, and returning False is the same as
an unchecked box.

http://www.WillyDev.Net

CR.NET Book by Bischof- Chapter 7 - Copyright 2003

Page 6 of 16

Figure 7-6. The section expert window.


Figure 7-7 shows the Border tab of the Format Editor dialog box. The properties on this dialog box
are much different from the Section Editor. This dialog box uses checkboxes, line styles and colors.

http://www.WillyDev.Net

CR.NET Book by Bischof- Chapter 7 - Copyright 2003

Page 7 of 16

Figure 7-7. The Format Editor'


s border tab.
The values for the line style and color are predefined constants within Basic syntax. The line style
property can have values such as DashedLine, NoLine, etc.. The color property can have values such as
Aqua, Yellow, etc.
When you open the Formula Editor, the predefined constants for the property you are working on are
listed in the Function Tree. This list is dynamic and it will not show the predefined constants for other
properties. For example, if you are modifying a line style property, the Function Tree will show the
different line styles, but wont list any colors. This is illustrated in Figure 7-8. If you are modifying a
color property, then it will show the available colors, but no line styles. This is illustrated in Figure 7-9.

http://www.WillyDev.Net

CR.NET Book by Bischof- Chapter 7 - Copyright 2003

Page 8 of 16

Figure 7-8. The Function Tree for line styles.

Figure 7-9. The Function Tree for colors.

Using the Default Attribute and the Current Field Value


The value that you assign to a property in design mode is the propertys default attribute. When you
assign a formula to that property, then you are overriding its default attribute. In most circumstances you
want to use the default attribute the majority of the time and only override it for special circumstances.
There are two ways of doing this: not specifying a value in the formula or using the keyword
DefaultAttribute.

http://www.WillyDev.Net

CR.NET Book by Bischof- Chapter 7 - Copyright 2003

Page 9 of 16

When you dont specify a value, you are letting Crystal Reports use what was specified in the
Format Editor. For example, you may want a field to be red if its value is less than the minimum
quantity, otherwise use the attribute specified in the Format Editor. You can use a formula like the
following:
If {Inventory.OnHand} < {InventoryItems.MinimumQty} Then
Formula = crRed
End If

Although this is perfectly acceptable, it isnt perfectly clear what the color will be if the condition
isnt true. As a second alternative you can use an Else statement and specify the result to be
DefaultAttribute. By doing this you are making it clear that the color will either be crRed or the default
attribute that is specified on the Format Editor. Using DefaultAttribute is totally optional, but it helps
clarify what attribute will be used. The new code would look like the following:
If {Inventory.OnHand} < {InventoryItems.MinimumQty} Then
Formula = crRed
Else
Formula = DefaultAttribute
End If

Looking at this example, you might notice that the current field you are formatting,
{Inventory.OnHand} is the same field that is specified in the If condition. If someone else is reading this
formula, it may not be obvious that this is what you are doing. To make it clear, and just to simplify the
formula, you can use a shortcut called CurrentFieldValue. This keyword returns the current value of the
field that is being formatted. In this formula, it is a nice feature, but it is essential when working with
Cross-Tab fields. Cross-Tab reports are discussed in Chapter 10. The formula would be modified to the
following:
If CurrentFieldValue < {InventoryItems.MinimumQty} Then
Formula = crRed
Else
Formula = DefaultAttribute
End If

The Highlighting Expert is a simplified version of the Format Editor. It gives you a wizard interface for
creating rules that modify the font and border of a field. Figure 7-10 shows an example of using the
Highlighting Expert for drawing a double box border around a field when its value is equal to USA.
The Sample column shows the result of what the field will look like after the rule has been applied. The
Condition column shows the rule that is being applied. There can be multiple rules applied.

http://www.WillyDev.Net

CR.NET Book by Bischof- Chapter 7 - Copyright 2003

Page 10 of 16

Figure 7-10. The Highlighting Expert window.


Personally, I dont recommend using the Highlighting Expert. There are two reasons for this. The
primary reason is that it can create confusion when maintaining a report. This is because there are now
two places where the formatting of an object can be modified. If you inherited this report from another
programmer and you want to determine if a field is going to have its format modified, you have to check
two places: the Format Editor and the Highlighting Expert. For a large report, this can add a lot of
additional work. The second reason is that the rules in the Highlighting Expert always override the rules
in the Format Editor. If you create a formula in the Format Editor for the font and also use the Highlight
Expert to modify the font, then the formula is ignored and only the Highlighting Expert is used. This is
most likely to happen when you inherit a report from another programmer who liked using the
Highlighting Expert. You might add a formula with the Format Editor and spend a lot of time trying to
debug it. But you wont be able to fix it until you remember to check the Highlighting Expert. When
using .NET, this tool has the potential to do more harm than good.
The Highlighting Expert was originally designed as an easy way for end users to modify the format
of a field without having to know how to program. It let them create formulas just by pointing and
clicking. Once an end user felt comfortable with programming logic, then they would graduate to adding
formulas with the Format Editor. As a .NET programmer, programming is what you do and you dont
have to rely on a simplified tool for assistance. Thus, I prefer to ignore it altogether and keep all my
functionality within the Format Editor.

!
When creating a report, Crystal Reports uses two different stages to calculate what will appear on the
report and how it will be displayed. This is referred to as the Two-Pass Report Processing Model. The
first pass performs specific functionality that will then be used during the second pass.
The first pass is used to read individual records one at a time and calculate any formulas that use
them. Formulas that do this only use the raw data from a database field or perform simple calculations
on it. As each record is read, the formulas are calculated and their results are stored in a temporary file.

http://www.WillyDev.Net

CR.NET Book by Bischof- Chapter 7 - Copyright 2003

Page 11 of 16

After the first pass is finished, Crystal Reports performs a second pass where it evaluates all
summary functions on this data. This isn'
t possible in the first pass because all the data had not been read
yet. But during the second pass that data is now in a temporary file and it can be evaluated and
summarized as a whole.
Give examples and fill in more detailed descriptions
What the Two-Pass model means to you is that where you place a formula on a report and the
functionality within that formula effects when that formula is evaluated and whether it returns the
expected value or not. A formula can be placed on any section of your report, but you should plan this in
advance so that you can guarantee the proper results. To determine where to place your formula, you
need to know the rules that Crystal Reports uses to evaluate functions. There are certain rules that are
applied by default. These rules are as follows:

A formula that only references variables (it doesnt use group/summary fields or
database fields) is evaluated before any records are read.

Formulas using database fields are evaluated while records are being read.

Formulas using group fields, summary fields, or page related fields (e.g. the page
number) are evaluated after the records are read and while the report is being printed.

You can'
t determine which formula within a section will be called first. This is because
formulas within the same section are not evaluated in any particular order.

There are times when the default rules listed above will not give you the results you desire. For
example, there may be a situation where you have two formulas in the same section and one formula
relies upon the other to be called first. According to the default rules listed above, you know that there is
no way to determine which one will be called first. You need some way to force one formula to be
called before the other. Fortunately, you can modify the default rules to fit your particular situation.
There are four keywords that let you set when a formula will be evaluated: BeforePrintingRecords,
WhileReadingRecords, WhilePrintingRecords, and EvaluateAfter. Add the appropriate keyword to the
beginning of a formula. These keywords are listed in Table 7-1.
Table 7-1. Evaluation Time Keywords
Evaluation Keyword
BeforeReadingRecords
WhileReadingRecords
WhilePrintingRecords
EvaluateAfter(formula)

Description

Evaluate the formula before any database records are read.


Evaluate the formula while reading the database records.
Evaluate the formula while printing the database records.
Evaluate after another function has been evaluated.

If you are trying to debug a formula that isnt returning the expected result, then you have to take
many things into consideration: does the formula only use variables; should the formula be put in a
different section; is the formula being evaluated while reading records or while printing records; does
the report use a grouping section that may be effecting the order of evaluation. This is a lot to think
about while debugging. You can help cut down on the amount of time spent debugging formulas if you
start out by following some general guidelines. The remainder of this section gives guidelines and
examples for you to think about when writing your formulas
Place formulas that reset variables to their default value in the Report Header or Group Header
section. This insures that they are called before the formulas in the detail section are evaluated.
Be careful when using formulas that only have variables in them. If they are cumulative in nature,
then you may need to force their evaluation time to be WhileReadingRecords. If the reports uses groups
then you may need to use the WhilePrintingRecords keyword.
The keyword BeforeReadingRecords cant be used with formulas that have database fields or

http://www.WillyDev.Net

CR.NET Book by Bischof- Chapter 7 - Copyright 2003

Page 12 of 16

grouping/summary fields in them.


When you place multiple formulas within the same section, you cant assume the order that they will
be executed in. If you need one formula to be evaluated before another formula (its result is used in
other formulas) then put the EvaluateAfter keyword in the dependent formula. The following example shows
how this is used. This formula relies upon the formula ParseName to take the {Customer.Name} field and
parse the first name and last name out of it. The values are put into the global variables FirstName and
LastName. This example formula returns the LastName variable so that it can be displayed on the report.
The ParseName formula isnt shown here.
EvaluateAfter({@ParseName})
Global LastName As String
Formula = LastName

Summary calculations are performed while printing records. They can only do their calculations on
formulas that were evaluated beforehand (i.e. while reading records). Thus, a formula that uses
WhilePrintingRecords cant have summary functions performed on it.
Of course, these guidelines wont be able to prevent every problem from happening, but they are
here to help give you a start in the right direction.
To illustrate the importance of using the proper keyword in a formula, this final example shows you
each stage of writing a formula and how the output is effected by the evaluation time keyword.
The report is a customer report that uses the Extreme.mdb database. The primary focus is the row
number in the first column. The row number is tracked using a variable called RowNumber. The
formula is as follows:
Global RowNumber As Number Dont use Local b/c that resets the variable
RowNumber = RowNumber + 1
Formula = RowNumber

Figures 7-11 shows the output of this report. Notice that all the row numbers are 1. This is because
the default rule states if a formula only has variables in it, then it will be evaluated before any records
are read. Even though this formula is placed in the detail section, it only gets evaluated once and it'
s
value never changes.

http://www.WillyDev.Net

CR.NET Book by Bischof- Chapter 7 - Copyright 2003

Page 13 of 16

Figure 7-11. Row Number example output with same row number.
To fix this problem, use the keyword WhileReadingRecords in the formula.
WhileReadingRecords
Global RowNumber As Number Dont use Local b/c that resets the variable
RowNumber = RowNumber + 1
Formula = RowNumber

Figure 7-12 shows that the row number is now accurate because the formula is evaluated every time
a record is read.

http://www.WillyDev.Net

CR.NET Book by Bischof- Chapter 7 - Copyright 2003

Page 14 of 16

Figure 7-12. Row Number example output with correct row numbers.
Lets modify the example so that the report uses a grouping section based on the country name.
Figure 7-13 shows that the report now groups by country and uses a group header. Unfortunately,
this change has introduced a bug in the report because the row numbers are now out of order. This is
because the row number is being calculated while the records are being read. After being read, the rows
get resorted based upon the group. As a result, the row numbers get resorted as well. To fix this we have
to change the formula so that the row number is being evaluated while the records are being printed. At
this point, the rows have already been re-ordered for the groups and this wont effect the RowNumber
variable.
WhilePrintingRecords
Global RowNumber As Number Dont use Local b/c that resets the variable
RowNumber = RowNumber + 1
Formula = RowNumber

http://www.WillyDev.Net

CR.NET Book by Bischof- Chapter 7 - Copyright 2003

Page 15 of 16

Figure 7-13. Row Number example output with grouping.


Figure 7-14 shows that the row number is now accurate. This example shows you that declaring
when a formula is evaluated can have a very big effect on its value.

http://www.WillyDev.Net

CR.NET Book by Bischof- Chapter 7 - Copyright 2003

Page 16 of 16

Figure 7-14. Row Number example output with grouping and correct row numbers.

Reports are used to display raw data to the user. But there are times when just displaying raw data isn'
t
enough to properly convey the information being presented. You need to write formulas for performing
additional calculations on the data as well as making the output dynamic. The Formula Editor is userfriendly tool that you use to create these formulas. The next two chapters show you how to get more out
of the Formula Editor by showing you how to use Basic syntax and the built-in formulas.

http://www.WillyDev.Net

You might also like