Lesson 5: Additional Formatting Objects 151
26. Verify your report is similar to the image below.
Figure 5-35 Exercise 5-5 Result
27. Save the report with the name My Employee Summary.
28. Leave the file open for the next exercise.
Copyright ©2017 Pathfinder Learning, LLP
152 Lesson 5: Additional Formatting Objects
Inserting Special Fields
Crystal Reports has the ability to insert metadata information into a report. Metadata can be thought of as data about
data. Metadata is information about the report. Page numbers, author name, current date and time, these are all
types of information about the report that can be added to any section.
All of these fields are referred to as Special Fields in Crystal Reports. The Field Explorer contains a library of all of
the Special Fields that can be added to the report.
Figure 5-36 Special Fields Category in Field Explorer
Special Fields Description
Displays the locale setting of the computer on which the report is
Field Name running.
Content Locale Shows the user id of the current Crystal Enterprise user, if available.
Shows the name of the current Crystal Enterprise user, if available.
Current CE User Id Shows the time zone of the user (if one exists).
Current CE User Name
Current CE User Time Shows the date that the report data was last refreshed.
Zone Shows the time that the report data was last refreshed.
Data Date Shows the time zone in which the data was last refreshed.
Data Time Shows the author listed in the Summary Info window.
Data Time Zone Shows the date that the report was created.
File Author Inserts the file path and name of the current report.
File Creation Date
File Path And Name
Copyright ©2017 Pathfinder Learning, LLP
Lesson 5: Additional Formatting Objects 153
Field Name Description
Group Number Numbers each group and displays it in the group header or group footer.
Group Selection Formula
Shows the group selection formula used to filter the groups displayed in
Horizontal Page Number the report.
Modification Date Numbers the horizontal pages created by report objects, such as OLAP
Modification Time grids and cross-tabs, which may extend over several horizontal pages.
Page N Of M
Page Number Shows the last date that the report was saved.
Print Date
Print Time Shows the last time that the report was saved.
Print Time Zone
Record Number Inserts the page number with a total page count into the report.
Record Selection Formula
Inserts the page number on each page in the report.
Report Comments
Shows the date that the report was printed.
Report Title
Shows the time that the report was printed.
Selection Locale
Total Page Count Shows the time zone in which the report was printed.
Table 5-1 Special Fields Assigns and displays a number for each record in the report.
Shows the Record Selection Formula used to select the records in the
report.
Shows the comments that you have entered into the Summary Info
window.
Shows the report title that you have entered into the Summary Info
window.
Shows the locale setting of the machine the report is running on.
Shows the total count of the pages in the report.
NOTE: When using the Page N of M or Total Page Count special fields, because all of the data in the report
must be processed in order to determine the total page count of the report, processing time will be increased.
Document Properties
Certain fields do not contain any information until manually added by the report designer. Fields such as:
File Author
Report Title
Report Comments
Copyright ©2017 Pathfinder Learning, LLP
154 Lesson 5: Additional Formatting Objects
These fields may be populated by accessing the document properties. To access the document properties,
click the File dropdown menu and choose Summary Info… The Summary tab in the Document Properties
dialog box contains all of the voluntary metadata fields.
Figure 5-37 Document Properties Dialog Box
Copyright ©2017 Pathfinder Learning, LLP
Lesson 5: Additional Formatting Objects 155
Exercise 5-6 Inserting Special Fields in a Report
This exercise will provide you with the opportunity to add special report fields to various sections of the
report.
1. Continuing with the My Employee Summary file from the previous exercise, switch to the Design tab.
2. Move the text box containing all of the employee information to the right side of the report.
3. Add a text box to the left of the employee information and type Record: and press ENTER.
4. In the Field Explorer, expand the Special Fields category.
5. Click and drag the Record Number special field and place it on the blank row in the text box that was
just added.
6. Drag and drop the Page N of M special field to the bottom center of the Page Footer section.
7. Center the Page N of M special field content.
8. Add a text box to the top left of the Page Header section.
9. Type Print Date: and add the Print Date special field after the colon.
10. Add a carriage return to start a new line in the text box and type Print Time: and
11. Drag and drop the Print Time special field after the colon.
12. Increase the height of the text box if necessary.
13. Preview the report.
Copyright ©2017 Pathfinder Learning, LLP
156 Lesson 5: Additional Formatting Objects
14. Verify your report is similar to the image below.
Figure 5-38 Exercise 5-6 Results
15. Save the My Employee Summary file.
16. Close the file.
Copyright ©2017 Pathfinder Learning, LLP
Lesson 5: Additional Formatting Objects 157
Challenge Exercise – Formatting and Filtering
Create a new report with the table Products. This report will display discontinued products that are still in
stock.
1. Create a new report.
2. In the Database Expert window, open the My Connections folder and choose the Northwind 2008
database connection.
a. Expand the category labeled Tables.
b. Select the table named Products.
c. Click OK.
3. Change the orientation to landscape.
a. File > Page Setup
b. Select Landscape.
c. Click OK.
4. In the details section, add the fields: ProductID, ProductName, QuantityPerUnit, RetailPrice,
UnitsInStock, UnitsOnOrder, ReorderLevel and Discontinued.
5. Add a report title.
a. Click File > Summary Info…
b. In the Title field, enter Products List.
c. Add your name to the Author field.
d. Click OK.
Figure 5-39 Document Properties
Copyright ©2017 Pathfinder Learning, LLP
158 Lesson 5: Additional Formatting Objects
6. Using the Special Fields Report Header is a good way to add the report header if it needs to be displayed
in more than one place. If you later change the report header text, it is updated everywhere.
a. On the Field Explorer, expand Special Fields.
Figure 5-40 Field Explorer – Special Fields
b. Drag the Report Title to the Report Header section and the Report Footer section. You decide where
to place them inside those sections.
c. Make them 3 inches long; this lets a longer report title display on one line.
Copyright ©2017 Pathfinder Learning, LLP
Lesson 5: Additional Formatting Objects 159
7. Format the Report Header’s Report Title.
a. Right click on Report Title and choose Format Field….
b. Choose the Common tab.
c. Click the check box for Can Grow.
d. Click OK.
8. Format the column headers.
a. Remove the underline from the column headers.
b. Make the font bold and select a color.
c. Make the headers a bit more readable by adding spaces between the words. You may need to make
some of the heading text objects taller to allow some of the headings to be two lines.
d. Select the box tool and draw a box around the column headings.
e. Right click on the box border and select Format Box…
i. Click the check box in front of Fill Color.
ii. Select a fill color of your choice.
iii. In the Border section, select the color of your choice.
iv. Click OK.
9. Create a text object at the right side of the Report Header section and type Report author (type a space
after author).
a. From the Field Explorer, in the Special Fields section, drag the File Author special field into that
text object after the text.
b. If needed, change the width so the entire author’s name displays.
10. Change Discontinued formatting from True or False to Yes or No.
a. In the details section right click on Discontinued and choose Format Field…
b. Click on the Boolean tab.
c. Click the Boolean Text: dropdown click and choose Yes or No.
d. Click OK.
11. Filter the report to display only Discontinued Products.
a. Click on Discontinued in the Details section.
b. Click the Select Expert
c. Choose is True.
d. Click New and choose Products.UnitsInStock.
e. Click OK.
Copyright ©2017 Pathfinder Learning, LLP
160 Lesson 5: Additional Formatting Objects
f. Choose is greater than.
g. Enter 0.
h. Click OK.
Figure 5-41 Select Expert - Record
12. We no longer need to display the Discontinued column (we added it to test the filter).
a. Right click both of the discontinued fields (column header and detail) and choose Format Field…
b. On the Common tab, click the check box for Suppress. This keeps the column listed (grayed out) in
the Design view and hidden in the Preview in case we need it later.
13. Using the Record Sort Expert, Sort by Products.UnitsInStock, descending.
14. Save the report as Products List.
15. Preview the report; if needed, change ProductName to Can Grow.
Figure 5-42 Challenge Exercise Results
Copyright ©2017 Pathfinder Learning, LLP
Lesson 5: Additional Formatting Objects 161
Challenge Exercise - Adding Fields to Text Objects
This challenge exercise will use the report that you created in the challenge exercise from lesson 4 and add
fields to text objects.
1. Open the challenge exercise My Orders Grouped and Summarized and save it as My North America
Orders Grouped and Summarized.
2. In Group Footer #2, replace the word country with the ShipCountry field.
a. Switch to Design view.
b. In each of the three text boxes, delete the word Country.
c. If needed, open the Field Explorer.
d. Click on ShipCountry and drag it to each text object where you just deleted Country.
3. In Group Footer #3, replace the word Customer with the ShipName field.
a. In each of the two text boxes, delete the word Customer.
b. Click on ShipName and drag it to each text object where you just deleted Customer.
4. In Group Footer #1, click in the Total Orders Shipped for Month text object. Replace the word Month
with the ShippedDate, formatted to display the full month name and 4 digit year.
a. In each of the three text boxes, delete the word Month.
b. Click on ShippedDate and drag it to each text object where you just deleted Month.
c. Format the ShippedDate: Select it and right click. Select Format{Orders.ShippedDate}…
d. Scroll down and select March 1999.
e. Click OK.
Figure 5-43 Shipped Date
Copyright ©2017 Pathfinder Learning, LLP
162 Lesson 5: Additional Formatting Objects
Figure 5-44 Format
5. Save and preview the report.
Figure 5-45 Challenge Exercise Results
Copyright ©2017 Pathfinder Learning, LLP
Lesson 6: Working with Formulas 163
Lesson 6: Working with Formulas
Unit time: 75 minutes
In this lesson, you will be introduced to:
1 Creating a Formula
2 The Formula Workshop
3 Simple Formulas
4 Explaining Null Values
5 String Formulas
Copyright ©2017 Pathfinder Learning, LLP
164 Lesson 6: Working with Formulas
Creating a Formula
Databases are fantastic tools. The ability to store information and then recall it with a query to form a report is of
great importance in the information age. But often, databases will not contain information for every query that may
be developed. In many cases the database will possess all of the ingredients necessary to reach a specific conclusion,
but lacks the direction or guidance to provide such information.
Consider the following scenario; your database contains the cost of an item as well as the price that item was sold.
The information it lacks is the profit made on the sale. This information needs to be included in the report.
One way of including this information in the report is to contact the database administrator and ask that a calculated
field be included in the database; this field would then be included in the repot. Although this is an option, it is often
the most costly and time consuming way to approach solving the problem. The nature of the database may not make
it easy to integrate new fields without the approval of multiple levels of management. This may require reworking
other portions of the database in order to accommodate the new feature.
The time and cost required to approve, develop, test, and deploy such a feature are often more costly than they are
worth. Such is the nature of complex data storage systems.
Another option is to build the calculated field yourself. This approach will capitalize on the fields already contained
in the database and involves no other personnel to implement.
As simply as you would ask a hand-held calculator what the profit portion of a transaction is, a formula in Crystal
Reports can perform the same task. The advantage of creating a formula in Crystal Reports is that the formula is
written once and it will apply to all records queried from the database.
Crystal Formula Syntax
Crystal Reports is equipped with over 300 pre-packaged formulas. Just like spreadsheet programs, a library
of functions is at the disposal of the report designer. These formulas have the ability to evaluate, transform,
and calculate virtually any type of data required. Provided your logic is sound and your database possesses
the necessary information, virtually any conclusion can be reached.
Prior to Version 8 of Crystal Reports, the syntax used to write formulas was a language known as Crystal
Syntax. With the introduction of Version 8 of Crystal Reports, the ability to write formulas in Basic Syntax
was introduced. Although not a perfect clone of the Visual Basic language, Basic Syntax was similar
enough to reduce the learning curve for designers with Visual Basic experience.
Reports can contain formulas written in either Crystal Syntax or Basic Syntax, or even a mixture of the two.
Most report designers will develop formulas using the syntax they are either most comfortable with or which
their business requirements demand.
Copyright ©2017 Pathfinder Learning, LLP
Lesson 6: Working with Formulas 165
Formula components and syntax
Formulas contain two critical parts: the components and the syntax. The components are the pieces that you
add to create a formula while the syntax is the rules that you follow to organize the components.
Creating a formula in Crystal Reports is like creating one in any spreadsheet application. You can use any of
the following components in your formula:
Fields
Fields from the database are always shown surrounded by braces. The below is subtracting 2 fields
from the Sales table.
Example: {Sales.SalePrice}-{Sales.ItemCost}
Numbers
Numbers are typically entered in clean; no commas or currency symbols. Decimal points are only
necessary when defining a fractional portion. If a currency symbol ($) is entered with the number,
the number will be automatically displayed with currency formatting.
Example: 1, 2, 3.1416, $500
Text
Text is entered surrounded by either single or double quotes. If you need to have the quotation
marks retained as part of the data, enclose the text in two sets of quotes.
Example: "Sale Price =", ":", "Discount Amount", ′ "The Man" ′
Operators
Operators are actions you can use in your formulas. Crystal Reports allows for the inclusion of
spaces before and after an operator to increase readability. The spaces will be ignored when the
formula is processed.
Example: + (add), - (subtract), * (multiply), / (divide), ^ (exponent/root), -x (negate)
Functions
Functions perform calculations such as sum, average, max, min, and count. Functions are followed
by a set of parenthesis. The function’s variables are contained within these parenthesis and
separated by commas. All functions available are listed with their arguments and are arranged by
their use.
Example: Round (x), Trim (x)
Copyright ©2017 Pathfinder Learning, LLP
166 Lesson 6: Working with Formulas
Other Formulas
In an attempt to reduce the repetitious construction of formulas, a formula can be used as a variable
within another formula. This provides the opportunity for nesting already calculated results into
calculations further down the report. This assists in more rapid development of formulas as well as
consistent modifications during formula maintenance. Formulas used in other formulas must be
enclosed in braces and preceded with an @ symbol.
Example: {@SubTotal} * 10%, {@SalesPrice} – {@Discount}
Comments
Comments are established by beginning a line with two forward slashes (//). Comments are an ideal
way of documenting formulas for easier understanding. Designers who will maintain your formulas
at a later date will be aided greatly by explanations of seemingly unconventional logical
constructions.
Example: // The following formulas was multiplied by 1.2 to account for the cost of living
allowance.
Capitalization
Crystal Reports is not case sensitive when reading formulas.
Returns and Spaces
The inclusion of spaces or hard returns (ENTER key) has no effect on the processing of formulas.
Crystal Reports literally removes all returns and spaces (except for spaces contained between
quotation marks.) The addition of spaces and returns helps the designer by making formulas and
long stretches of code more readable.
The one area that will cause an error is if a return is inserted between quotation marks.
Copyright ©2017 Pathfinder Learning, LLP
Lesson 6: Working with Formulas 167
The Formula Workshop
The Formula Workshop serves as both warehouse and construction site for all of your formulas in Crystal Reports.
Formulas are created, edited, and managed in the Formula Workshop.
The Formula Workshop also contains the controls that determine the formula syntax used during editing (Crystal
Syntax vs. Basic Syntax) as well as settings for determining how Null database values are handled (discussed later in
the chapter.)
The Formula Workshop can be launched by various methods.
Clicking the Formula Workshop button on the Experts toolbar.
Clicking the Report dropdown menu and select Formula Workshop…
Figure 6-1 Formula Workshop via Report Dropdown Menu
Creating a formula through the Field Explorer.
Figure 6-2 Adding a New Formula
Copyright ©2017 Pathfinder Learning, LLP
168 Lesson 6: Working with Formulas
Layout of the Formula Workshop
There are three main components that make up the Formula Workshop:
Toolbars
Workshop Tree
Formula Editor
Figure 6-3 Formula Workshop Components
Toolbars
All of the functional controls for the Formula Workshop are located on the toolbars. Several of these
tools will be explored in the upcoming pages. Others are discussed in more advanced courses.
Workshop Tree
The Workshop Tree is where all of the designer-created formulas are stored. This allows for easy
navigation between the Formulas, SQL Expressions, and other assorted custom formulas.
Copyright ©2017 Pathfinder Learning, LLP
Lesson 6: Working with Formulas 169
Formula Editor
The Formula Editor is a component of the Formula Workshop. The Formula Editor is made up of
several areas that contain elements used in the construction of formulas. The three main categories
that these elements fall into are:
Tables and Fields
Functions
Operators
Figure 6-4 Formula Editor Components
These three areas can be resized, closed, maximized, or restored like traditional windows. To
perform these operations, click one of the control buttons in the upper-left corner of the area.
Copyright ©2017 Pathfinder Learning, LLP
170 Lesson 6: Working with Formulas
Figure 6-5 Minimize and Close Controls
If an area is closed and needs to be reopened, click one of the tree show/hide buttons located on the
Formula Workshop toolbar.
Figure 6-6 Formula Workshop Show Tree Controls
The Formula Editor also contains the edit area where functions are created and edited.
Tables and Fields
This area displays a list of all database fields and report formulas currently in use by the
report. This area also provides access to the following:
every database, table, and field to which the report is connected
designer-created formulas
group names
summary fields
running totals
parameters
Copyright ©2017 Pathfinder Learning, LLP
Lesson 6: Working with Formulas 171
Figure 6-7 Tables and Fields List
Functions
This area is the library of all functions available in Crystal Reports. The functions are
grouped categorically. These groups can be expanded by clicking the plus sign to the left
of the function category. Once expanded, the category will display all of the functions
contained within that category.
Figure 6-8 Function Library
Some functions have several ways that they may be implemented; they may have different
combinations of variables that allow them to work in different fashions. Clicking the plus
sign to the left of the function name will display the various ways in which a function can
operate.
Figure 6-9 Function Formats Example
For a complete explanation of any function and the various ways the function may be
implemented, click once on a function in the Function Tree and press the F1 key. If a
function has variations on the way it may be implemented, select one of the function
variations before pressing the F1 key on your keyboard.
Copyright ©2017 Pathfinder Learning, LLP
172 Lesson 6: Working with Formulas
Figure 6-10 Function Help Example
Operators
The Operators area contains a categorical grouping of all of the Crystal Reports operators.
Accessing the operator or obtaining help is done in the same manner as when using
functions.
Figure 6-11 Operators Library
Copyright ©2017 Pathfinder Learning, LLP
Lesson 6: Working with Formulas 173
Some of the more widely used operators, such as Add, Subtract, Multiply, Divide, If-Then-
Else, And, Or, and Concatenate can be found here.
Formula Editor Area
The Formula Editor Area is where you build or edit your formula. All of the fields,
operators or functions can be added to the Formula Editor Area by either double-clicking the
item or by dragging and dropping the item into the editor area. You can also manually type
all the data into the editor area.
Copyright ©2017 Pathfinder Learning, LLP
174 Lesson 6: Working with Formulas
Simple Formulas
Before you attempt to develop complex formulas it is a good idea to start with something simple. When creating
formulas it is a good idea to first write your logic out on a piece of paper and run some test data through a calculator
(or spreadsheet program if you are comfortable with one.)
Be certain to follow the Order of Operations when writing formulas.
Order Processed Operator Symbol Mnemonic
1st Parenthesis ( ) (Shift 9 & 0) Please
2nd Exponents ^ - Caret (Shift 6) Excuse
3rd Multiplication * - Asterisk (Shift 8) My
4th Division / - (Forward Slash) Dear
5th Addition + Aunt
6th Subtraction - Sally
Table 6-1 Order of Operations
All too frequently, the formula designer will forget these rules and receive unexpected results with their formulas.
As an example, the formula 3+4*5 yields 23, whereas (3+4)*5 yields 35.
Checking for Syntax Errors in Formulas
Crystal Reports is equipped with a syntax checking feature to
help with diagnosing errors in formulas. After a formula has
been constructed, click the Check button. If all goes well,
the following No errors found. message will be displayed.
If anything appears suspicious or illogical, the syntax checker Figure 6-12 Check Results – No Errors
will display a an appropriate message identifying the issue. For Figure 6-13 Check Result – Error(s)
example, if a formula were to contain an open parenthesis ( but
does not contain a corresponding close parenthesis ), the
following error message will appear.
Copyright ©2017 Pathfinder Learning, LLP
Lesson 6: Working with Formulas 175
Exercise 6-1 Add a Subtotal Formula to the Report
This exercise will provide you with experience creating formulas in the Formula Workshop’s Formula
Editor. You will also check the integrity of your formulas as well as add the formulas to the report.
1. Browse to the location of the saved class files and open the folder named Exercise Files\Lesson 06.
2. Select the E6-1 Sales Record file and then click Open.
3. Switch to the Design tab.
4. In the Field Explorer, right-click on the Formula Fields category and select New…
5. In the Formula Name dialog box, type Subtotal and click OK.
Figure 6-14 –Formula Name Box
6. In the Field Tree, expand the Report Fields category.
7. Double-click OrderDetails.UnitPrice to add the field to the formula edit area.
8. Type an * (asterisk) after the newly added field in the formula edit area.
9. In the Field Tree, double-click OrderDetails.Quantity to add the field to the formula edit area.
10. The completed formula should look like the following:
{OrderDetails.UnitPrice}*{OrderDetails.Quantity}
Figure 6-15 Formula Workshop Example Formula
Copyright ©2017 Pathfinder Learning, LLP
176 Lesson 6: Working with Formulas
11. Click the Check button to verify the integrity of the formula.
12. Click the button.
13. The Subtotal formula field will now appear in the Field Explorer.
Figure 6-16 Field Explorer with New Formula
14. Click and drag the newly created Subtotal field from the Field Explorer and place it to the right of the
Quantity field in the Details section of the report. Observe that the Subtotal formula field is preceded
with an @ sign. This helps to differentiate a formula field from a database field.
Figure 6-17 Formula Added to Details Section
15. Preview the report
16. Verify your report is similar to the image below.
Figure 6-18 Exercise 6-1 Results
17. Save the My Sales Record file.
18. Leave the file open for the next exercise.
Copyright ©2017 Pathfinder Learning, LLP
Lesson 6: Working with Formulas 177
Exercise 6-2 Add a 15% Discount Formula to the Report
In this exercise, you will create a formula that calculates a discount amount. This field will be added to your
report from the previous exercise.
1. Continuing with the My Sales Record file from the previous exercise, switch to the Design tab.
2. In the Field Explorer, right-click on the Formula Fields category and select New…
3. In the Formula Name dialog box, type Discount and click OK.
Figure 6-19 Formula Name Box
4. In the Field Tree, double-click Subtotal to add the formula field to the formula edit area.
5. Type an * (asterisk).
6. Following the asterisk, type .15.
7. The completed formula should look like the following:
{@Subtotal}*.15
Figure 6-20 Formula Workshop Example Formula
8. Click the Check button to verify the integrity of the formula.
9. Click the button.
Copyright ©2017 Pathfinder Learning, LLP
178 Lesson 6: Working with Formulas
10. The Discount formula field will now appear in the Field Explorer.
Figure 6-21 Field Explorer with New Formula
11. Click and drag the newly created Discount field from the Field Explorer and place it to the right of the
Subtotal field in the Details section of the report.
Figure 6-22 Formula Added to Details Section
12. Preview the report.
13. Verify your report is similar to the image below.
Figure 6-23 Exercise 6-2 Results
14. Save the My Sales Record file.
15. Leave the file open for the next exercise.
Copyright ©2017 Pathfinder Learning, LLP
Lesson 6: Working with Formulas 179
Recycling Formula Fields
One of the advantages of creating formula fields is that a specific formula only needs to be created once,
even if the same logic is needed within another formula. If a formula needs to calculate an event that has
already been calculated by another formula, the original formula field can be referenced instead of writing
the same logic again. There is no need to reinvent the wheel.
Example: Suppose a 15% discount formula field has been created and displayed within the report. If
another formula calculating the total needs to factor in the 15% calculation, the discount logic need not be re-
evaluated. The original discount formula field can be referenced.
Not only is this more efficient from a formula writing perspective, it also improves processing time because
the report does not need to calculate portions of a formula multiple times.
Copyright ©2017 Pathfinder Learning, LLP
180 Lesson 6: Working with Formulas
Exercise 6-3 Add a Total Formula to the Report
In this exercise, you will create a formula that calculates a total. This field will be added to your report from
the previous exercise.
1. Continuing with the My Sales Record file from the previous exercise, switch to the Design tab.
2. In the Field Explorer, right-click on the Formula Fields category and select New…
3. In the Formula Name dialog box, type Total and click OK.
Figure 6-24 Formula Name Box
4. In the Field Tree, double-click Subtotal to add the formula field to the formula edit area.
5. Type a - (minus sign).
6. In the Field Tree, double-click Discount to add the formula field to the formula edit area.
7. The completed formula should look like the following:
{@Subtotal}-{@Discount}
Figure 6-25 Formula Workshop Example Formula
8. Click the Check button to verify the integrity of the formula.
9. Click the button.
Copyright ©2017 Pathfinder Learning, LLP
Lesson 6: Working with Formulas 181
10. The Total formula field will now appear in the Field Explorer.
Figure 6-26 Field Explorer with New Formula
11. Click and drag the newly created Total field from the Field Explorer and place it to the right of the
Discount field in the Details section of the report.
Figure 6-27 Formula Added to Details Section
12. Preview the report.
13. Verify your report is similar to the image below.
Figure 6-28 Exercise 6-3 Results
14. Save the My Sales Record file.
15. Close the file.
Copyright ©2017 Pathfinder Learning, LLP
182 Lesson 6: Working with Formulas
Explaining Null Values
One of the most nebulous concepts in Crystal Reports is the idea of what constitutes a Null. At its simplest, a field
containing a Null is a field that has never contained anything; it has no value. If a field once held information, but
that information has been removed, it is said to be empty. Empty is not the same as Null. With Empty, there is an
awareness of what was once there, i.e. a number or a word (string). A Null signifies that information has never
existed and therefore cannot be imagined.
If a designer were to write an IF formula that stated if a condition was not met, then populate the field with nothing
(usually represented as two double quotes); this would be SOMETHING. There is at a base level an awareness of
empty. In comparison, a field that has never been populated would be considered Null.
Nulls can produce what appear to be errors in data. Most databases today have the ability to prevent the occurrence
of Nulls in their data. A common strategy when establishing a database field is to set a Not Null attribute, thereby
requiring a value to be present in every occurrence of the field. As stated, this is something that databases can
require. It is not uncommon to encounter data where Nulls have been permitted.
Crystal Reports – How Nulls are handled
Formulas written with Crystal Syntax have two options for handling Nulls encountered in data:
Exception for Nulls
Default Values for Nulls
The mechanism for selecting one of the two options is via a drop-down list at the top of the Formula
Workshop.
Figure 6-29 Null Handling Control
The default behavior of Crystal Reports is to generate an exception when encountering Null values. This
means that the information in the record will be skipped. If the Default Value for Nulls option is selected,
Crystal Reports will replace all string-type fields with blanks strings and all number-type fields with zeroes.
This will prevent the record from being skipped and will display the formula with any information contained
in the fields.
Copyright ©2017 Pathfinder Learning, LLP
Lesson 6: Working with Formulas 183
To change the default Null handling behavior, click File and choose Options… On the Formula Editor
tab, select the desired behavior from the Null Treatment dropdown list.
Figure 6-30 Setting Null Handling Defaults
Handling Nulls via formulas
The following scenarios will demonstrate three different methods for displaying data containing Nulls.
Displaying Raw Fields with Nulls
The objective is to display an employee’s address information. As with many databases, addresses
are broken into the following components:
Address1
Address2
City
Region (state)
ZIP
Country
Copyright ©2017 Pathfinder Learning, LLP
184 Lesson 6: Working with Formulas
If we examine our data source, we will discover that many of the employees do not contain
information in the Address2 field. In addition, the non-US entries do not contain Region (state)
information. All of these fields with missing data are interpreted by Crystal Reports as Null values.
Figure 6-31 Examples of Nulls in Source Data (Access Table)
If we were to construct an address block in the Details section of the report, the entries with the
missing data would manifest themselves as empty spaces in the data.
Figure 6-32 Text Box with Address Fields
Copyright ©2017 Pathfinder Learning, LLP
Lesson 6: Working with Formulas 185
Figure 6-33 Blank Areas Where Nulls Exist
Because the myriad of fields in the Details section make for a cluttered design, and the blanks in the
data create a very non-uniformed look to our report, we need to come up with an intelligent way of
displaying the address information. This is where formulas enter the picture.
Using Formulas to Display Fields with Nulls
Instead of loading the Details section with a series of database fields, it would make more sense to
build a formula containing the required fields. In this way, we can achieve the same result with a
single formula field in the Details section. As an added benefit, if we ever require the additional
presence of the address block in our report, we can simply reuse the formula and our work is done.
A formula like the following would collect all of the necessary address block fields and display them
in the appropriate order.
Figure 6-34 Formula to Construct Address Block
Copyright ©2017 Pathfinder Learning, LLP
186 Lesson 6: Working with Formulas
NOTE: Since Crystal Syntax ignores tabs and carriage returns, we cannot simply add a
carriage return in our code to make the Address2 field appear on the second line. The
function ChrW() allows us to display a single character from the ASCII table, including
characters that are not normally accessible via traditional keyboard buttons. The code for
executing a carriage return is 13, hence the use of the ChrW(13) instruction.
By adding the newly constructed formula field to our reports, we are left with a much tidier looking
Details section and we will produce the following output.
Figure 6-35 Address Block Formula Added to Details Section
Figure 6-36 Missing Records Due to Null Fields
Copyright ©2017 Pathfinder Learning, LLP
Lesson 6: Working with Formulas 187
As is readily apparent, many if not most of the records are missing the address information. The
reason for this is because any field (i.e. Address 2 or Region) that contains a Null value will generate
an exception. In other words, it will be rejected and not displayed in the report.
This problem can be easily rectified by editing the Address formula. The formula itself does not
need to be modified, but the behavior when encountering Null values needs to be changed.
Figure 6-37 Changing Null Handling Behavior
By changing the Null behavior from Exceptions for Nulls to Default Values for Nulls the following
result will occur.
Figure 6-38 Visable Addresses with Nulls
Copyright ©2017 Pathfinder Learning, LLP
188 Lesson 6: Working with Formulas
By populating all of the Null values with either zeroes or blanks (depending on the data type) we are
able to now see all of the database records. The only issue with this address block is that we are still
seeing the blank fields and commas after cities with no regions.
Using Formulas to Intelligently Display Fields
If we were to construct a formula with some decision-making capability, we could examine the
contents of the potentially blank fields and decide when to display them in the report.
The primary means of examining fields for a set condition is with an IF Statement. The IF
Statement will perform a test to determine the true or false nature of a situation. If the result of the
test is true, the IF Statement will execute a set of instructions. If the result of the test is false, a
different set of instructions is executed.
We perform IF Statement decisions all day, every day. Most are made at an automatic level. If you
are driving down the road and you encounter a traffic light, you check the state of the light to
determine your driving behavior. If the light is green, you press the accelerator pedal, but if the light
is red you press the brake pedal. The test, in this case the light, determines your action, to accelerate
or to brake.
A formula like the following would perform all of the necessary tests and plot all of the appropriate
actions based on the outcomes of each test.
Figure 6-20 Address Block to Detect Null Fields
Copyright ©2017 Pathfinder Learning, LLP
Lesson 6: Working with Formulas 189
If we examine the logic in layman terms, it reads as follows:
Step 1: Test to see if the Address2 field is empty. The IsNull function will return true if a field is
Null or return false if a field is not null.
Step 2: If the Address2 field is Null (true), print the Address1 field. If the Address2 field is not
Null (false), print the Address1 and Address2 fields with each field on a separate line.
Step 3: Start a new line with a ChrW(13) instruction and then test to see if the Region field is
empty.
Step 4: If the Region field is Null (true), print the City field. If the Region field is not Null
(false), print the City and Region fields separated by a comma and a space.
Step 5: Start a new line and print the PostalCode field.
Step 6: Start a new line and print the Country field.
By replacing the original address block in the Details section with the newly created formula we
arrive at a list that eliminates all of the missing fields and produces a more uniform, professional
looking report.
Figure 6-40 Address Block Formula Added to Details Section
Copyright ©2017 Pathfinder Learning, LLP
190 Lesson 6: Working with Formulas
Figure 6-41 Result of Formulaic Address Block (with Nulls)
With this technique, each record’s address will be displayed regardless of the Null exception handler
setting assigned to the Address formula.
Copyright ©2017 Pathfinder Learning, LLP
Lesson 6: Working with Formulas 191
Exercise 6-4 Handling Nulls (Part 1)
In this exercise, you will create a report that includes a formula that produces an address field. The data for
the addresses will contain null values which will produce undesirable results when previewing your report.
The following exercise will provide a strategy for counteracting those undesirable results.
1. From the Start Page, under the START A NEW REPORT banner, click Blank report.
2. From within the Database Expert, in the Available Data Sources section (left) expand the My
Connections folder. Expand the Northwind 2008.mdb entry.
3. Expand the category labeled Tables.
4. Select the table named Suppliers and add the table to the list of Selected Tables.
5. Click OK to close the Database Expert dialog box.
6. Save the file with the name My Address Nulls.
7. In the Field Explorer, expand the Database Fields folder.
8. Expand the Suppliers table.
9. Add the SupplierName by clicking and dragging the field from the Field Explorer to the Details section.
10. Create a formula named FullAddress1 with the following logic:
{Suppliers.Address}
+ ChrW(13) +
{Suppliers.City} + ", " + {Suppliers.Region}
+ ChrW(13) +
{Suppliers.PostalCode}
+ ChrW(13) +
{Suppliers.Country}
11. Check the formula for errors.
12. Click Save and close to close the Formula Workshop.
13. Increase the height of the Details section to approximately one inch.
14. Add the FullAddress1 formula to the Details section.
15. In the Details section, increase the height of the FullAddress1 field to one inch.
16. Preview the report. Observe that the majority of the records are missing their addresses due to the
interference of Null values in the data.
17. Return to the Design tab.
Copyright ©2017 Pathfinder Learning, LLP
192 Lesson 6: Working with Formulas
18. Right-click on the FullAddress1 formula and select Edit Formula…
19. Click anywhere in the formula in the lower panel of the window. From the Null Handling dropdown at
the top of the screen, change the setting from Exceptions for Nulls to Default Values for Nulls.
20. Click Save and close.
21. Preview the report.
22. Verify your report is similar to the image below.
Figure 6-42 Exercise 6-4 Results
Observe that all of the addresses are now visible. The issue now is that blank spaces occur where Null
values exist, and commas are visible where Regions are missing. These issues will be addressed in the
following exercise.
23. Save the file as My Address Nulls file
24. Leave the file open for the next exercise.
Copyright ©2017 Pathfinder Learning, LLP
Lesson 6: Working with Formulas 193
Exercise 6-5 Handling Nulls (Part 2)
This exercise will provide a strategy for counteracting the undesirable results produced by null values in the
previous exercise.
1. With the My Address Nulls file from the previous exercise, switch to the Design tab.
2. Create a formula named FullAddress2 with the following logic (NOTE: Pay special attention to the red
opening and closing parenthesis for the IF statement):
{Suppliers.Address}
+ ChrW(13) +
(IF IsNull({Suppliers.Region}) Then
{Suppliers.City}
Else
{Suppliers.City} + ", " + {Suppliers.Region})
+ ChrW(13) +
{Suppliers.PostalCode} + ChrW(13) +
{Suppliers.Country}
3. Check the formula for errors.
4. Click Save and close to close the Formula Workshop.
5. Add the newly created FullAddress2 formula to the right of the Address1 formula in the Details section
and increase the height of the field to one inch.
6. Preview the report and compare the updated formula results to the original formula results. Observe the
greater efficiency of the FullAddress2 logic.
Copyright ©2017 Pathfinder Learning, LLP
194 Lesson 6: Working with Formulas
7. Verify your report is similar to the image below.
Figure 6-43 Exercise 6-5 Results
8. Save the file as My Address Nulls.
9. Close the file.
Copyright ©2017 Pathfinder Learning, LLP
Lesson 6: Working with Formulas 195
String Formulas
In Crystal Reports, text values are called strings. In Exercise 6-4 we learned that in a formula we can include
multiple fields by adding a “+” between them, and that any text enclosed in “ ” is displayed as it is shown in the “ ”.
For example, {Suppliers.City} + “, ” + {Suppliers.State} tells the formula to display the City, a comma and space
and then the state.
We can also use only part of a text string using the subscript operators [ ]; place the [] immediately after the field.
Use it to specify a single character or a range of characters, such as from 2 to 5. FirstName[1] returns the first
character of the first name.
Often reports include formulas with dates or numeric amounts and text in a formula. To include dates or numbers
along with text in a formula, it is necessary to convert the dates or numeric amounts to text. Doing this also lets you
format them.
Format strings for Date, Time, and DateTime values
The following characters are used to create format strings for Date, Time, and DateTime values. Note that
only the ways of displaying the month — M, MM, MMM, MMMM —are case sensitive since the lowercase
m and mm indicate minutes.
Character How they are used Table 6-2 Date
Time characters
d day of month without leading zero for single digits for conversion
dd day of month with leading zero for single digits
ddd day of week as a three letter abbreviation
dddd full name of day of week
M month without leading zero for single digit
MM month with leading zero for single digit
MMM month as three-letter abbreviation
MMMM full name of month
yy last two digits of year
yyyy full four digits of year
h hours without leading zeros for single digits (12 hour)
hh hours without leading zeros for single digits (12 hour)
H hours without leading zeros for single digits (24 hour)
HH hours with leading zeros for single digits (24 hour)
m minutes without leading zeros for single digits
mm minutes with leading zeros for single digits
s seconds without leading zeros for single digits
ss seconds with leading zeros for single digits
t, tt single character or multiple character a.m./p.m. string
Copyright ©2017 Pathfinder Learning, LLP
196 Lesson 6: Working with Formulas
Using formulas to manipulate dates
Two commonly used functions to add or subtract dates are DateAdd and DateDiff. Use these when you need
to consider the number of days in a month and leap years in the calculations. They are also used to display
the result in a certain interval such as years or months.
DateAdd is used to add intervals of time, such as a specified number of weeks, months or years,
or other intervals to a given date.
DateDiff finds the difference between two dates in the indicated interval, such as in weeks,
months or years.
Interval Type value Description
yyyy Year
q Quarter (3-month period)
m Month
y Day of year
d Day
w Weekday
ww Week (7-day period)
h Hour
n Minute
s Second
Table 6-3 DateAdd and DateDiff intervals
Copyright ©2017 Pathfinder Learning, LLP
Lesson 6: Working with Formulas 197
Exercise 6-6 Working with Strings and Dates
In this exercise, you will create a report that includes a formula to combine the employee’s first initial, last
name and title. You will also display the employee’s age, hire date and 15-year anniversary date.
1. From the Start Page, under the START A NEW REPORT banner, click Blank Report.
2. From within the Database Expert, in the Available Data sources section (left), expand the My
Connections folder. Expand the Northwind 2008.mdb entry.
3. Select the table named Employees and add the table to the list of Selected Tables.
4. Click OK to close the Database Expert dialog box.
5. Save the report as My Employment History.
6. In the Field Explorer, expand the Database Fields folder.
7. Expand the Employees table.
8. Create a new formula. In the Field Explorer right click Formula Fields and select New…
9. In the Formula Name dialog box, type Employee ID Name Title and click OK.
Figure 6-44 Formula Name
10. In the Formula Workshop Field Tree, expand the Reports Fields category.
11. Create the following formula
ToText({Employees.EmployeeID},0,"") + "-" +
{Employees.FirstName}[1] + ". " + {Employees.LastName} + " - " + {Employees.Title}
The ToText({Employees.EmployeeID},0,"") converts the EmployeeID to text. The 0 tells Crystal
Reports 0 decimal places and the “” means no thousands separator.
The {Employees.FirstName}[1] uses only the first character of the FirstName.
Copyright ©2017 Pathfinder Learning, LLP
198 Lesson 6: Working with Formulas
Click Save and Close. Crystal Reports checks the formula for syntax errors; if there are no errors, it
saves and closes the formula.
If Crystal Reports detects an error, you will see
Figure 6-45 Error in Formula
12. Click No to return to the formula. Identify and fix the error, then again click Save and Close.
Tip: you can save a formula with an error, just be sure to correct it or the report will not work properly.
13. Add the formula to the report: click and drag the Employee ID Name Title formula from the Field
Explorer to the Details section at the left margin.
14. Save and preview the report. Adjust the width of the column so nothing is truncated (cut off).
Tip: if needed, right click on the field, choose Format Field… and on the Common tab check Can
Grow.
15. Calculate the employee’s age and display it in years. Use the DateDiff function as it will perform the
calculation and we can tell it to display the result in years. We can learn what arguments (information)
the DateDiff function requires by locating it in the Formula Workshop’s function list. Create a new
formula. In the Field Explorer right click Formula Fields and select New…
16. In the Formula Name dialog box, type Age and click OK.
17. Expand the Functions list (the column to the right of the Report Fields) by clicking the +.
18. Expand the Date and Time group by clicking its +.
19. Expand the DateDiff function. It describes the required and optional arguments in the ( ): intervalType,
startDateTime, endDateTime are required. The second DateDiff includes the required intervalType,
startDateTime, endDateTime and adds an optional argument, which we do not need. Double click the
first of the two DateDiff options; it is copied to the formula editor below and the cursor is positioned
inside the (),
Copyright ©2017 Pathfinder Learning, LLP
Lesson 6: Working with Formulas 199
Figure 6-46 Functions Tree
20. As the Function list shows us, the first argument is the intervalType. As noted in the DateAdd and
DateDiff intervals table 6-3, “yyyy” tells DateDiff to calculate the difference in years. Type "yyyy"
(include the "").
21. Move the cursor after the comma and double click the BirthDate in the Employees table. This is under
the Report Fields area.
22. Move the cursor after the comma and double click CurrentDate in the Date and Time Functions area.
Tip: you can also type the functions instead of double clicking on them in the Functions area. When
learning the functions, selecting them from the Functions area may help you understand what
arguments (information) they require.
23. The final formula is DateDiff ("yyyy",{Employees.BirthDate} ,CurrentDate)
24. Click Save and Close.
25. Add the formula to the Details area next to the Employee ID.
26. Add the HireDate to the report after Age. Click on HireDate in the Field Explorer and drag it to the
detail section.
27. Create a formula named 15 year anniversary. Right click on Formula Fields in the Field Explorer and
choose New…
Copyright ©2017 Pathfinder Learning, LLP
200 Lesson 6: Working with Formulas
28. Type 15 year anniversary and click OK.
29. The DateAdd function requires the interval (“yyyy”), the amount of the interval (15) and the start date.
The final formula is: DateAdd ("yyyy",15,{Employees.HireDate} )
30. Click Save and Close.
31. Add the 15 year anniversary date to the report after the HireDate. Click on 15 year anniversary in the
Field Explorer and drag it to the detail section.
32. Add a report title, Employee 15 year anniversary dates
33. Save and preview the report. The report should resemble the image below.
Figure 6-47 Exercise 6-6 Results
34. Make any needed formatting changes.
Figure 6-48 Exercise 6-6 Results
35. Close the report.
Copyright ©2017 Pathfinder Learning, LLP