Crystal Reports Xi - Advanced 1418861472pv

155
 Crystal Reports XI: Advanced Instructor’s Edition NOT FOR PRINTING OR INSTRUCTIONAL USE

description

Crystal Report for XI

Transcript of Crystal Reports Xi - Advanced 1418861472pv

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    1/155

    C r y s t a l R e p o r t s X I :

    A d v a n c e d

    Instructors Edition

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    2/155

    ILT Series

    COPYRIGHT Axzo Press. All rights reserved.

    No part of this work may be reproduced, transcribed, or used in any form or by any meansgraphic, electronic, ormechanical, including photocopying, recording, taping, Web distribution, or information storage and retrieval

    systemswithout the prior written permission of the publisher.

    For more information, go to www.courseilt.com.

    Trademarks

    ILT Series is a trademark of Axzo Press.

    Some of the product names and company names used in this book have been used for identification purposes only andmay be trademarks or registered trademarks of their respective manufacturers and sellers.

    Disclaimer

    We reserve the right to revise this publication and make changes from time to time in its content without notice.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    3/155

    C o n t e n t s

    Introduction ii

    Topic A: About the manual............................................................................... ivTopic B: Setting student expectations .............................................................. ixTopic C: Classroom setup.................................................................................xiTopic D: Support...............................................................................................xv

    Selecting data 1-Topic A: Parameter fields ................................................................................1-Topic B: Defining report elements ................................................................. 1-1Unit summary: Selecting data ......................................................................... 1-

    Advanced formulas and functions 2-Topic A: Running totals................................................................................... 2-

    Topic B: Variables........................................................................................... 2-Topic C: Advanced functions ......................................................................... 2-1Topic D: Constructs ........................................................................................ 2-2Unit summary: Advanced formulas and functions.......................................... 2-2

    Charts and maps 3-Topic A: Working with charts ......................................................................... 3-Topic B: Creating maps .................................................................................. 3-1Unit summary: Charts and maps .....................................................................3-2

    Formatting complex reports 4-Topic A: The Section Expert ........................................................................... 4-

    Topic B: Advanced conditional formatting .................................................... 4-1Topic C: Objects ............................................................................................. 4-2Unit summary: Formatting complex reports ................................................... 4-2

    Alerts and subreports 5-Topic A: Report alerts...................................................................................... 5-Topic B: Subreports......................................................................................... 5-Unit summary: Alerts and subreports.............................................................. 5-1

    Data management features 6-Topic A: The Business Objects Enterprise Repository.................................... 6-Topic B: The Workbench ................................................................................6-

    Unit summary: Data management features ...................................................... 6-

    Advanced data access techniques 7-Topic A: ODBC data sources........................................................................... 7-Topic B: SQL and the Database Expert..........................................................7-1Unit summary: Advanced data access techniques........................................... 7-2

    Course summary S-Topic A: Course summary ............................................................................... S-Topic B: Continued learning after class ..........................................................S-

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    4/155

    ii Crystal Reports XI: Advanced

    Quick reference Q-1

    Glossary G-1

    Index I-1

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    5/155

    xvi Crystal Reports XI: Advanced

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    6/155

    1

    U n i t 1

    Selecting data

    Unit time: 95 minutes

    Complete this unit, and youll know how to

    A Use parameter fields to preview data, ba

    on specified criteria.

    B Select data by using a pick list and a dat

    range, and create cascading parameters

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    7/155

    12 Crystal Reports XI: Advanced

    Topic A: Parameter fields

    Explanation With Crystal Reports, you can useparameter fieldsto view only the data you want tosee. You can create a parameter field to select a specific value and return only the datain the report that matches that value, or you can specify a range of values. In this way, areport will change depending on which values are selected from the parameter field.

    Using parameter fields

    A parameter field prompts the user to enter a value and then displays data based on thatvalue. For example, a user may want to display sales data for only those years whenproduct sales were greater than $100,000. You can create a parameter field that promptsthe user to specify that or any other amount.

    When creating a parameter field, you can specify a discretevalue or a rangeof values.If you specify a discrete value, users can enter only a single value in the parameter field.If you use a range, however, users will be prompted to specify lower and upper limitsfor the parameter field. The report will display the values that fall within the specified

    range. For example, to display sales between 2003 and 2005, a user can specify theseyears as the lower and upper limits of a range.

    You can also use multiple parameter fields. For example, if you want to display data forthe sales of a particular product in a particular year, you can create multiple parameterfields to prompt the user for this information.

    There are several ways to use a parameter field. They include:

    Placing it in the report

    Including it in a conditional formatting formula

    Including it in a record selection formula

    To create a parameter field:

    1 Open a report.

    2 In the Field Explorer, select Parameter Fields.

    3 Click New, to open the Create Parameter Field dialog box.

    4 Enter a name and prompting text for the parameter field, and then specify avalue type. The name identifies the parameter field and will appear in the FieldExplorer. The prompting text prompts the user to enter a value. The value typespecifies the type of data that can be entered in the field, such as string, number,or date time.

    5 Click OK.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    8/155

    Selecting data 1

    Exhibit 1-1: The Create New Parameter dialog box

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    9/155

    14 Crystal Reports XI: Advanced

    Do it! A-1: Creating a parameter field

    Heres how Heres why

    If the registration wizardopens, tell students toclick Register Later.

    1 Start Crystal Reports XI Choose Start, All Programs, Crystal Reports XI.

    Close the Workbench If necessary.Tell students that theylllearn about theWorkbench in anotherunit.

    2 Open Orders From the current unit folder.

    Save the report as My Orders

    3 In the Field Explorer, selectParameter Fields

    Click (The New button is on the toolbar in the FieldExplorer.) To open the Create New Parameterdialog box.

    Tell students that they canauto-hide the FieldExplorer, if they wish.

    Tell students thatthe regional manager

    wants to run separatereports for each retailer,when needed.

    4 In the Name box, enter RetailerName

    To specify a name for the parameter field.

    Tell students that the datatype must match the field.

    In the Type list, verify that Stringis selected

    (As shown in Exhibit 1-1.) This is the parameterfields data type.

    Click OK To close the dialog box and create the new field.

    5 Open the Select Expert (Choose Report, Select Expert, or click theSelect Expert button on the Experts toolbar.) Toopen the Choose Fields dialog box.

    In the Report Fields list, selectRetailers.Retailer_Name

    Click OK The Select Expert dialog box appears.

    6 From the list, select is equal to Another list appears.

    From the second list, select{?Retailer Name}

    To specify that only those records with theretailer name equal to the parameter valueRetailer Name appear when the report ispreviewed. The question mark (?) before thefield name indicates that it is a parameter field.

    Click OK To close the Select Expert.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    10/155

    Selecting data 1

    7 Click To preview the report. The Enter Values boxappears, prompting you to enter a value.

    Tell students that entriesare not case-sensitive.

    8 In the Enter Retailer Name box,type spice world

    The name of the retailer whose records you wto see.

    Click OK To close the prompt and select the data.

    9 Observe the report Only the records of the specified retailer appe

    Update the report

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    11/155

    16 Crystal Reports XI: Advanced

    Wildcards

    Explanation Its possible to select records even if youre not sure of the exact value you want toenter at the prompt. You can use wildcards, or a portion of the value name, in aparameter field to return the data youre looking for. For example, you might want toselect records based on a name, but you may not be able to remember the exact nameyou want to select. By using wildcards, you can enter a value and see data that

    approximately matches that value.

    A wildcard character is indicated by an asterisk (*). You can use a wildcard character atthe beginning or the endor bothof your selection criterion. For example, selectingrecords based on the value *dill*would return all the product names that include theword "dill," such as "dried dill," "dill weed," and "dill seed."

    Do it! A-2: Using wildcards to select data

    Heres how Heres why

    1 Open the Select Expert Youll modify the parameter field RetailerName to select records based on an approximate

    match to the value entered.

    2 From the first list, select is like

    Tell students thatthe regional manager

    finds it difficult toremember all the retailernames, and wants to typepartial names to get thereport. From the second list, select

    {?Retailer Name}

    Click OK To close the Select Expert and apply the change.A dialog box appears.

    3 Click Use Saved Data To close the dialog box.

    4 Refresh the report Another dialog box appears.

    Select Prompt for newparameter values

    Click OK To open the Enter Values dialog box.

    Tell students to be sure totype the asterisks.

    5 Edit the Enter Retailer Name toread *spice*

    To return all records where the retailer namecontains the word Spice.

    Click OK To close the prompt and select the new records.

    6 Observe the report The records show only those retailers whose

    names contain the word Spice.

    7 Delete the selection criterion In Select Expert, press Delete, and click OK.

    Select Refresh Data To return all the records in the database.

    Update the report

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    12/155

    Selecting data 1

    Edit masks

    Explanation An edit mask limits the type of data you can enter in a parameter field. For example,you might create a report that prompts the user for an employees Social Securitynumber. Social Security numbers will be displayed in a specific format (###-##-####where # represents a number when you use an edit mask to ensure that the user entersthe number in that format.

    You can specify an edit mask only for fields using the String data type.

    There are several characters that you can use to create an edit mask. These are calledmasking characters. The following table describes some of the masking characters.

    Character Description

    A The user can enter any alphanumeric character, but the character musbe in the parameter value.

    a The user can enter any alphanumeric character but does not need toenter a character in place of the masking character a.

    L The user can enter only letters and must enter a letter in place of themasking character.

    C The user can enter any character or space but does not need to enter acharacter or space in place of the masking character.

    ? The user can enter a letter but does not need to enter a letter in place the masking character.

    & The user can enter any character or space and must enter a character space in place of the masking character.

    #The user can enter any digit, space, or plus or minus sign but does noneed to enter anything in place of the masking character.

    9 The user can enter a number or a space but does not need to enteranything in place of the masking character.

    0 The user can enter only numbers and must enter a number in place ofthe masking character.

    \ The character entered after this appears as a literal. For example, if yspecify the edit mask 0\L0, then the parameter value will consist odigit, the letter L, and another digit. This character is useful only wheyou need to include a reserved masking character as a part of theparameter value.

    < The characters entered after this character are converted to lowercase

    > The characters entered after this character are converted to uppercase

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    13/155

    18 Crystal Reports XI: Advanced

    Character Description

    Password Here you specify the word Password for an edit mask. When you entercharacters for this type of mask, asterisks (*) appear in place of the actualcharacters. This is useful for creating conditional formulas in which youspecify that some fields of the report will appear only when a password isentered.

    Separatorcharacters

    These include periods (.), commas (,), colons (:), semicolons (;), hyphens (-),and slashes (/). Other characters cannot replace these characters, and theyform a part of the parameter value. For example, in the case of a SocialSecurity number, the hyphens (-) cannot be replaced by other characters, andthey form a part of the parameter value.

    To apply an edit mask to a field:

    1 Open the Create Parameter Field dialog box.

    2 Specify a name, prompting text, and data type for the parameter field.

    3 In the Edit mask box, enter the masking characters.

    4 Click OK to set the edit mask for the parameter field.

    5 Click OK to create the parameter field. When you refresh the data in theparameter field, the Enter Parameter Values dialog box will display the editmask in the Discrete Value box.

    Do it! A-3: Applying an edit mask to a parameter field

    Heres how Heres why

    1 Create a new parameter field (In the Field Explorer, click the New button.) Toopen the Create Parameter Field dialog box.

    In the Name box, enter RetailerCode

    In the Value type list, String should be selected.

    Tell students thatthe regional managerwants to view the product

    sales for a specific retailercode. We will apply anedit mask to a newparameter field becausethe retailer code is in aspecific format.

    Under Options, in the Prompt textbox, type Enter the RetailerCode for which you wantto display order details:

    2 Under Options, in the Edit maskbox, enter R000

    This field can now take only a string that startswith R and is followed by three numbers.

    3 Click OK To set the edit mask.

    Click OK Retailer Code is added to Parameter Fields inthe Field Explorer.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    14/155

    Selecting data 1

    4 Open the Select Expert dialog box The Choose Field dialog box appears.

    Under Report Fields, selectOrders.Retailer_code

    Youll apply the Retailer Code parameter to thfield.

    Click OK An Orders.Retailer_code tab activated.

    5 From the list, select is equal to

    From the second list, select{?Retailer Code}

    To view the records with the Retailer Codeequal to the parameter field value.

    Click OK The Enter Values prompt appears.

    6 In the box, enter T042

    Click OK The entered value is not accepted, because yohave not entered all of the required charactersYou specified an R in the edit mask, followedby three digits.

    7 In the box, enter R042

    Click OK A message box appears, asking if you want touse saved data or refresh the data.

    Click Refresh Data The data for the Retailer Code R042 appears ithe report.

    8 Delete the selection criterion In Select Expert, press Delete.

    9 Refresh and update the report

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    15/155

    110 Crystal Reports XI: Advanced

    Topic B: Defining report elements

    Explanation You can create parameters that provide users with a list or a range of default values tochoose from. This can save time by helping the user to avoid manually typing in a valueand possibly making a mistake.

    If a parameter field has a list of values, you can provide apick listfrom which users canchoose a particular value. The pick list is also useful in the case when the user is notaware of all the values of the parameter field. You can add values to the list from eitheran existing text file or a database field. By adding values from a field, you can providethe user with the exact field values. If you use a text file, you can add only those valuesthat are stored in the file, which might differ from the exact values.

    Pick lists

    To create a pick list from a database field:

    1 Create a new parameter field. (You can also modify an existing parameter field.)

    2 From the Value Field list, select the field from which you want to create the picklist.

    3 From the Description Field list, select a related field, if desired.

    4 In the Actions drop-down menu, select Append all database values, to add thevalues to the pick list.

    5 Click OK to close the Create New Parameter dialog box and create the pick list.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    16/155

    Selecting data 1

    Do it! B-1: Using a pick list in a parameter field

    Heres how Heres why

    1 In the Field Explorer, from theParameter Fields list, selectRetailer Name

    2 Click The Edit button is on the Field Explorer toolb

    3 In the Value Field list, from theOrders table, selectRetailer_code

    4 In the Description Field list, fromthe Retailers table, selectRetailer_name

    5 Click the Actions drop-down list To display a menu.

    Choose Append all databasevalues

    To create a pick list with all the retailer codesand names.

    Tell students that thisaction may take a momentor so to complete.

    Click OK To close the Edit Parameter dialog box.

    6 Open the Select Expert To open the Choose Field dialog box.

    In the Report Fields list, from theRetailers table, selectOrders.Retailer_code

    Click OK To close the Choose Field dialog box and opethe Select Expert.

    7 From the list, select is like

    From the second list, select{?Retailer Name}

    Click OK To close the Select Expert and open the EnterValues prompt.

    8 Under Enter Retailer Name, clickthe drop-down arrow

    To display the pick list of retailers.

    Select Outlander SpiceCorner

    Click OK To close the prompt and display the requestedrecords.

    9 Update the report

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    17/155

    112 Crystal Reports XI: Advanced

    Selecting multiple values from a pick list

    Explanation You can set up a pick list to allow users to select more than one value from it. Forexample, you may want users to be able to select records containing data for two ormore different sales years, or two or more different products.

    To set up a multiple-value pick list, open the New Parameter or Edit Parameter dialogbox, and change the setting for Allow multiple values from False to True.

    Do it! B-2: Modifying a pick list to allow multiple values

    Heres how Heres why

    1 Select the Retailer Nameparameter field

    In the Field Explorer.

    2 Click To open the Edit Parameter: Retailer Namedialog box.

    3 Under Options, select Allow

    multiple values

    Click False To display a list.

    From the list, select True

    4 Click OK To close the dialog box and apply the newsetting. The Enter Values prompt appears.

    5 From the Available Values list,select R003 Hot Spices

    Click To move the value R003 Hot Spices into the

    Selected Values list.

    6 Select R042 Spice Cornerand move it into the SelectedValues list

    Select the value from the Available Values listand click the Move button.

    Click OK To close the dialog box and select the records.

    7 Observe the report It contains records for the two selected retailers.

    Update the report.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    18/155

    Selecting data 1

    Date ranges

    Explanation You can select records based on a range of dates. This is useful when, for example, ywant to see data that shows individual department earnings during a particular year, othe product sales for a particular month.

    To create a parameter field based on a date range:

    1 Open the Create New Parameter dialog box (you can also edit an existingparameter).

    2 From the Type list, select Date Time.

    3 Enter a name and prompting text for the parameter.

    4 Create your selection criteria based on a date field.

    Do it! B-3: Using a date range

    Heres how Heres why

    1 Create a new parameter fieldnamed Order Date

    From the Type list, select DateTime

    2 Under Options, edit the PromptText to read Click theCalendar icon to selectorder date

    Tell students to scrolldown the list.

    3 In the Options list, change thesetting for Allow range values toTrue

    4 Click OK To save the settings and close the dialog box.

    5 Open the Select Expert

    Delete the current selectioncriterion

    Press the Delete button.

    6 Create a new selection criterionbased on the Orders.Order_Datefield, where the operator is equalto the Order Date parameter field.

    Click OK The Enter Values dialog box appears.

    7 Observe the screen The Enter Values dialog box contains two arefor entering selection values.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    19/155

    114 Crystal Reports XI: Advanced

    8 In the Start of Range area, clickthe Calendar icon

    To open a calendar.

    Select January 1, 2005 as the Startof Range value

    The date appears in the Start of Range box.Tell students to use thearrow icons in thecalendar to select themonth and year, and to

    click on the day within thecalendar to select the day. Select June 30, 2005 as the End ofRange value

    Click the Calendar icon in the End of Rangearea and select the date.

    9 Click OK To close the Enter Values prompt.If a dialog box appears,tell students to clickRefresh Data

    10 Observe the report Only those records with order dates fallingwithin the specified date range are returned.

    Update the report

    Dynamic prompts and cascading parameters

    Explanation The prompts you define for a parameter can be eitherstaticor dynamic. A static promptis used when the values associated with it reside in the report itself and do not change. Adynamic prompt can be used when its associated values exist in a data source outsidethe report, and can change depending on the parameter being prompted for.

    A dynamic prompt can contain cascading lists of values, meaning that selecting a valuefrom one list filters the values that appear in the following list, and so on. For example,you might want to select records for retailers in a particular city, but you also need toknow what state that city is in. You would therefore create the first list based on thestate value, and when a state is selected, a list of city values for that state will appear.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    20/155

    Selecting data 1

    Do it! B-4: Creating a cascading parameter

    Heres how Heres why

    1 Create a new parameter namedRetailer Products

    2 In the List of Values options,select Dynamic

    The Static options disappear.

    3 In the Prompt Group Text box,enter Select a retailer, thena product

    4 Under Choose a Data Source,verify that Newis selected

    Click Insert To open a list of report fields.

    5 From the Retailers table, selectRetailer_name

    This will be the first prompt.

    Click as shown

    To create the first parameter.

    6 Click in the second Value box To open the list of report fields.

    From the Orders table, select

    Product_description

    The retailer choice will limit the products that

    are available to choose when prompted.

    In the second Parameters box,click to create the secondparameter

    Click OK To close the dialog box and create theparameter.

    7 Open the Select Expert

    Delete any current selection

    criteria

    Youll create new selection criteria based on t

    new parameter field.

    8 Click New

    Select Retailers.Retailer_name and click OK

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    21/155

    116 Crystal Reports XI: Advanced

    9 From the list, select is equal to

    From the second list, select{?Retailer Products Retailer_name}

    10 Click NewTo open the Choose Field dialog box.

    From the Fields list, selectOrders.Product_description

    Click OK To return to the Select Expert.

    11 From the list, select is equal to

    From the second list, select{?Retailer Products-Product_description}

    12 Click OK To close the Select Expert.

    13 Preview the report The Enter Values prompt appears.

    14 In the first prompt, select AllTimes Spices

    This retailer has purchased only a limitednumber of products.

    In the second prompt, click thedrop-down arrow

    To view the list of products that All TimesSpices has purchased.

    15 Choose Anise Seeds To view just the orders for Anise Seeds.

    Click OK To close the prompt and retrieve the records.Only those orders for Anise Seeds are returned.

    16 Update and close the report

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    22/155

    Selecting data 1

    Unit summary: Selecting data

    Topic A In this topic, you learned about creating new parameter fields. You also learned howuse wildcardsin parameters, and to apply edit masksto parameter fields.

    Topic B In this topic, you learned how to create a pick listfor a parameter field, and how to

    select multiple values from pick lists. Next, you learned how to use a date rangein aparameter field. Finally, you learned how to create cascading parameters.

    Independent practice activity

    In this practice activity, youll create a parameter field that will help you select recorbased on Membership type, and modify the field to allow for various input options.

    1 Open Membership List from the current unit folder.

    2 Save the report as My membership list.

    3 Create a parameter field called Membership Type. Edit the prompt text to readPlease Enter the membership type:

    4 Create a selection criterion based on the new parameter field. Preview the report,and enter a membership type in the Enter Values box to return records for thatmembership type.

    5 Modify the selection criterion to allow for wildcards. In the Enter Values box, typ*b*to return records.

    6 Modify the parameter to display a pick list showing all membership types. Refrethe report data and choose Prompt for new parameter values. Choose a membershtype from the pick list to return records for that type.

    7 Modify the parameter to allow for the selection of multiple values. Test themodification by choosing two values in the Enter Values dialog box.

    8 Create a new dynamic parameter named Members. In the Prompt Group Text botype Choose a membership type, then a member.

    9 For the first value, choose strMembershipType. Create an appropriate promptintext.

    10 For the second value, choose strLastName Create an appropriate prompting text

    11 Delete all current selection criteria in the Select Expert and create new criteria baon the new parameter fields.

    12 Test the selection criteria by entering values in the prompt.

    13 Update and close the report.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    23/155

    118 Crystal Reports XI: Advanced

    Review questions

    1 What is the purpose of a parameter field?

    To select a specific value, or a range of values, and return only the data in the report thatmatches those values.

    2 What are some ways you can use a parameter field?

    Placing it directly in a report

    Including it in a conditional formatting formula

    Including it in a record selection formula

    3 When youre not sure of the exact value you want to specify in a parameter prompt,you can:

    A Enter all the values you can think of in the prompt.

    B Press the ? key.

    C Use a wildcard (a portion of the value with an *) in the prompt.

    D Delete the parameter field so that the prompt doesnt appear.

    4 True or false: You can create an edit mask for a parameter field of any data type.

    Falseonly the string data type can use an edit mask.

    5 A good reason to provide a pick list in a parameter field would be:

    To help the user avoid typing in values manually and possibly making a mistake

    To provide a list of values to the user who may not be aware of all the values available

    6 What data type would you choose for a date range parameter field?

    Date Time

    7 A parameter field that prompts for one value and then supplies a list of relatedvalues to choose from is called a:

    A Static parameter

    B Cascading parameter

    C Number parameter

    D Pick list

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    24/155

    2

    U n i t 2

    Advanced formulas and functions

    Unit time: 120 minutes

    Complete this unit, and youll know how to

    A Create, modify, and reset running totals.

    B Create complex formulas by using

    variables, arrays, and ranges.

    C Create formulas by using multiplefunctions and Evaluation Time functions

    D Specify conditions for repeating sets of

    steps in formulas by using For and Whilloops.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    25/155

    22 Crystal Reports XI: Advanced

    Topic A: Running totals

    Explanation When creating a report, you might need to calculate an incremental total for a particularfield on each record. You perform this function by using running totals. You canidentify a running total field by the # sign at the beginning of the running total fieldsname.

    Create a running total

    To create a running total field:

    1 In the Field Explorer, select Running Total Fields.

    2 Click the New button, to open the Create Running Total Field dialog box, asshown in Exhibit 2-1.

    3 Complete the dialog box and click OK. The field is then listed in the FieldExplorer, under Running Total Fields.

    4 Select the field you just created, and drag it onto the report.

    Exhibit 2-1: The Create Running Total Field dialog box

    Exhibit 2-2: A portion of the report showing a running total

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    26/155

    Advanced formulas and functions 2

    Do it! A-1: Creating a running total

    Heres how Heres why

    1 Open Retailer Order Information In the current unit folder.

    Save the report as My retailer

    order information

    2 In the Field Explorer, selectRunning Total Fields

    3 Click To open the Create Running Total Field dialobox.

    4 In the Running Total Name box,type Totals

    5 From the Available Tables andFields list, select Total Amount

    Total Amount is a formula field.

    Click To move the Total Amount field into the Fieldto summarize box.

    In the Type of summary box,verify that sumis selected

    Click OK To close the dialog box and create the field.

    6 Drag the new Totals field to theDetails section of the report, asshown

    Position it to the right of the Total Amount fie

    Drag the Totals field heading tothe Group Header #1 section

    To align it with the other field headings.

    7 Preview the report A running total of the product sales is calculatfor the Totals field, as shown in Exhibit 2-2.

    Update the report

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    27/155

    24 Crystal Reports XI: Advanced

    Modify running totals

    Explanation You modify a running total field by using the Edit Running Total Field dialog box. Youcan edit a running total field to make calculations only with specific values or to displayinformation about certain values only.

    This dialog box appears when you select the running total and click the Edit button inthe Field Explorer dialog box. Another method of displaying this dialog box is by right-clicking the running total field and choosing Edit Running Total from the shortcutmenu.

    Exhibit 2-3: A portion of the report showing the modified Totals field

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    28/155

    Advanced formulas and functions 2

    Do it! A-2: Modifying a running total

    Heres how Heres why

    The regionalmanager wants to trackrunning totals of products

    where the Unit Price isgreater than $2.00.

    1 Switch to Design view

    2 In the Details section, right-clickthe Totals field

    To display a context menu.Tell students that

    they can also select thefield in the Field Explorerand click the Edit button. Choose Edit Running Total To open the Edit Running Total Field dialog

    box.

    3 Under Evaluate, select Use aformula

    Youll create a formula to show only those itewhose unit price is more that $2.00.

    Click To open the Formula Workshop.

    4 In the Formula text window, type{Orders.Unit_price}>2

    5 Click To check the formula for errors.

    Save the formula and close theFormula Workshop

    On the Formula Workshop toolbar, click Saveand close.

    6 Click OK To close the Edit Running Total field dialogbox. A warning message appears.

    Click Yes To close the warning message and apply thenew formula.

    7 Preview the report The Totals field displays repeating data until aunit price over $2.00 is found, as shown inExhibit 2-3.

    Update the report

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    29/155

    26 Crystal Reports XI: Advanced

    Resetting running totals

    Explanation You may want a running total to reset depending on when a group or a field changes.For example, you might want to reset the running total of a product sale depending onthe retailer buying the product. To reset a running total, edit the running total field byselecting an option in the Reset area.

    Do it! A-3: Resetting a running total based on a group

    Heres how Heres why

    1 Observe the report The Totals field displays a running total of allsales in all states with unit prices over $2.00.Youll reset the running total to start over witheach state, including all unit prices.

    2 For the Totals field, open the EditRunning Total Field dialog box

    Right-click the field in the Details section andchoose Edit Running Total from the contextmenu.

    3 Under Evaluate, select For eachrecord

    To include all the unit prices.

    4 Under Reset, select On changeof group

    To reset the running total when the state groupchanges.

    5 Click OK To close the dialog box and apply the newsettings.

    6 Preview the report The Totals field now shows a running total ofsales for each state.

    7 Delete the Totals field In the Field Explorer.

    Update the report

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    30/155

    Advanced formulas and functions 2

    Topic B: Variables

    Explanation In Crystal Reports, you can perform complex calculations by using formula componesuch as variables. A variable acts as a placeholder for a specific value. Unlike staticvalues, variables can be assigned different values again and again.

    Variables in a formula

    All the examples in thisunit deal with creatingformulas in Crystalsyntax. Students canalso use Basic syntaxto write formulas inCrystal Reports;however, that syntax isnot covered in thiscourse.

    You might need to create formulas that calculate values based on other calculatedvalues. For example, you have a report that displays production costs and total sales feach year and you want it to display profit as a percentage of production cost. To do you first need to calculate the profit by subtracting production cost from total sales. Ycan then use this value to calculate the profit percentage.

    To perform this type of calculation, you would store the first calculations result so ycould use it in the second calculation. You can do so by using a variable. When aformula comes across a variable, the formula searches for and uses the value attachedthat variable. You can store only one value at a time in a variable.

    Each variable must have a name by which you can identify it. This name cannot be thsame as any keyword, function, or operator in Crystal syntax. Variables must also beassigned a data type, such as number, string, or currency.

    Variable declarations

    To use a variable in a formula, you must first declarethe variable, or specify its datatype and name. The syntax for variable declaration is as follows:

    ;

    The following table describes some of the data types that Crystal Reports uses.

    Item Description

    NumberVar Numeric variable

    CurrencyVar Currency variable. (The values that you store in this type ofvariable are preceded by the currency symbol.)

    StringVar String (text) variable

    TimeVar Variable that stores time values in an hours-minutes-seconds format, with AM or PM at the end

    DateVar Variable that stores date values in a month-day-year format

    For example, heres how you would declare a numeric variable named X:

    numberVar X;

    To store a value in a variable, you use this syntax:

    := ;

    For example, this is how you would assign the value 5 to variable X:

    X := 5;

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    31/155

    28 Crystal Reports XI: Advanced

    Variable scope

    Scopedefines the degree to which the variable can be used in other formulas. Youspecify a variables scope when you define the variable. Crystal Reports offers threelevels of scope: local, global, and shared.

    Local variablescan be used in only a single formula. To declare a local variable, use thefollowing syntax:

    Local numberVar X;

    Global variablescan be used throughout the main report. The value will be available toall formulas that declare it, but it will not be available within any subreports. To declarea global variable, use the following syntax:

    Global numberVar X;

    You can also declare a global variable by defaultjust omit the Global keyword.

    Shared variablesare available throughout the main report and all subreports. To declarea shared variable, you precede the declaration with the keyword Shared.

    Exhibit 2-4: A portion of the report using the Discounted Price formula

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    32/155

    Advanced formulas and functions 2

    Do it! B-1: Declaring and using a variable in a formula

    Heres how Heres why

    1 Switch to Design view Youll create a formula that uses variables todetermine what month an order was placed, anthen applies a discounted rate to that order.

    2 Create a new formula field calledDiscounted Price

    In the Field Explorer. To open the FormulaWorkshop.

    Outlander Spicesdiscounts some of theiroverstocked products in

    certain months. Theregional manager wants torun reports that apply thediscount for a givenmonth.

    3 In the Operators list, expandVariable Declarations

    4 Double-click NumberVarx:=y

    (NumberVar is the variables data type.) Toinsert the variable into the formula.

    In the Formula text window, afterNumberVar, type OrderMonth

    Position the insertion point afterthe equal sign

    Youll add a second value.

    5 In the Functions list, expandDate and Time

    Double-click Month(x) To add the function to the formula.

    6 In the Report Fields list, double-click Orders.Order_Date

    The formula will calculate the month in whichan order was placed.

    7 Position the insertion point afterthe semi-colon and presse

    To move to the next line of the formula.

    8 Type the rest of the formula asshown

    The code for this formulacan be copied from theDiscount Price textdocument in the currentunit folder.

    If the order date falls in April and June, thediscount rate will be 75%. If the order date fain July and September, the discount rate will b50%. If the order date is after September, thediscount will be 25%.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    33/155

    210 Crystal Reports XI: Advanced

    9 Check the formula for errors

    Save the formula and close theFormula Workshop

    10 Place the Discounted Price field in

    the Details section of the report,as shown

    Move the field heading to theGroup Header #1 section

    To align it with the other field headings.

    11 Format the field heading to matchthe other headings

    Resize and reposition the field Move it slightly to the left.Tell students that theyllbe adding another field in

    the next activity. 12 Preview the report The discounted price appears, based on themonth the order was placed, as shown in Exhibit2-4.

    Update the report

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    34/155

    Advanced formulas and functions 2

    Arrays

    Explanation You may need to use multiple values in a formula. For example, you may have sixcommission percentages you use based on a salespersons performance. You might aneed to change the percentages at some point. Youd have to reflect these changes at the places where the percentages are used in formulas. This process would be easier iyou store the percentages in variables; however, because a variable can store only a

    single value, youd need to use six variables to store the six percentage values, addinthe formulas complexity.

    In this type of situation, you can use an array. An arrayis a kind of variable used tostore multiple values of a single data type. To use an array in a formula, you need todeclare the array. The syntax is as follows:

    array := [Value1,Value2,Value3,....]

    For example, heres the syntax for declaring an array named Y that stores four numervalues:

    numberVar array Y := [15,20,25,30];

    The values that are stored in the arrayin this example, 15, 20, 25, and 30are calle

    the array elementsand are referred to by a common name followed by a subscript. Asubscriptspecifies the position of an element in an array. For example, in the array Ythe subscript for element 15 is 1; for element 20, it is 2; and so on. To use the value 1in the formula, you can refer to it as Y[1]. The subscript of the first value of an array always 1.

    The subscript of the last element is called the upper boundof the array. Its the same the number of elements in an array. To find out the value of the upper bound of anarray, you can use a function called UBound. The syntax of the function is:

    UBound ();

    This function returns the number of elements in an array as a numeric value, which cbe useful when youre using looping constructs.

    Exhibit 2-5: The formula edited to use an array variable

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    35/155

    212 Crystal Reports XI: Advanced

    Do it! B-2: Using an array variable in a formula

    Heres how Heres why

    1 Switch to Design view Youll modify the current formula to use anarray variable to apply the discount.

    2 In the Field Explorer, select theDiscounted Price field

    Click To open the Formula Workshop FormulaEditor Discounted Price dialog box.

    3 Position the insertion point asshown

    Presse To add a new line for the formula.

    4 In the Variable Declarations list,double-click NumberVar

    array x: = [y, z, ]

    To add the variable to the formula.

    5 Place the insertion point to the leftof the colon

    If necessary.

    Type PercentDiscount

    6 Enter the remaining values asshown

    7 Edit the remainder of the formula As shown Exhibit 2-5.

    8 Check the formula for errors

    The code for this formulacan be copied from theArray Discount text file inthe current unit folder.

    Save the formula and close theFormula Workshop

    9 Preview the report The discounted price is displayed.Tell students that thediscounted prices are thesame as in the previousactivity, just applied withthe array variable.

    Update the report

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    36/155

    Advanced formulas and functions 2

    Range variables

    Explanation You use a range in a formula to check whether a value lies between specified limits. Fexample, in a sales report, you might want to find the names of salespersons whose tosales were between $10,000 and $20,000. A range has two end points: a lower limit aan upper limit. All the values that lie within these limits form part of the range.

    Heres the syntax for declaring a range variable:

    range := to

    For example, to declare a range called sales with a data type of currency, you wouluse this syntax:

    currencyVar range sales := 10000 to 20000;

    To check whether a value lies within a range, you can use either the equal sign (=) orthe in keyword. For example, the following code will display the text between thequotes if the value of the salesvalue field lies within the sales range:

    if Salestable.salesvalue in sales then "The sales value is between 10000 to 20000"

    Exhibit 2-6: A formula for displaying text based on range variables

    Exhibit 2-7: A portion of the report after the activity

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    37/155

    214 Crystal Reports XI: Advanced

    Do it! B-3: Using a range variable in a formula

    Heres how Heres why

    1 Switch to Design view Youll use a range variable to display the totaldiscount.

    The regionalmanager wants to seewhich discounts are being

    applied. 2 Create a new formula field calledDiscount To open the Formula Workshop Formula Text Discount box.

    3 In the Variable Declarations list,double-click NumberVarrange x := y to z

    To add the range variable to the formula.

    4 Place the insertion point to the leftof the colon

    If necessary.

    Type Qtr1

    Place the insertion point after theequal sign

    Type 1 to 3

    To complete the variable declaration.

    5 Add the following variabledeclarations as shown

    Tell students that they cantype the declarationsdirectly in the Formula textwindow.

    6 Place the insertion point after thefinal semi-colon

    Presse To begin a new line.

    7 Type the rest of the formula As shown in Exhibit 2-6.

    8 Check the formula for errors

    The code can be insertedfrom the Range Text textdocument in the currentunit folder.

    Save the formula and close the

    Formula Workshop

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    38/155

    Advanced formulas and functions 2

    9 Place the Discount field to theright of the Discounted Price fieldin the report

    Move the field heading to theGroup Header #1 section

    To align it with the other headings.

    Format the heading to match theother headings

    10 Preview the report It should look like Exhibit 2-7.

    Update and close the report

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    39/155

    216 Crystal Reports XI: Advanced

    Topic C: Advanced functions

    Explanation To help you create formulas, Crystal Reports provides several types of built-infunctions, including String, Summary, Date/Time, and Evaluation Time. You can usethese functions by themselves or combine them to form more complex formulas. Forexample, you can calculate the average sales for the past five years and then round offthe values to whole numbers. You can create formulas specific to your needs and speedup creation of reports by combining these functions.

    Using multiple functions in a formula

    You can create a formula by using multiple functions to calculate a value. You can alsocombine multiple functions, field values, and text in a formula.

    Combining functions, field values, and text

    To combine different types of values in a formula, you use an ampersand (&), which iscalled the concatenationoperator. It combines values from two different types of fields

    and returns a string type value. You can display this value in the formula field. Considerthe following example:

    stringVar DisplayValue;DisplayValue := "The sales for the year 2002 are " & Salestable.Sales

    This code will combine a string and a sales value, and then store the resulting string inthe DisplayValue variable.

    Exhibit 2-8: The report showing average profit for 1995 to 2005

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    40/155

    Advanced formulas and functions 2

    Do it! C-1: Creating a formula by using multiple functions

    Heres how Heres why

    1 Open Estimated profit From the current unit folder.

    Save the report as My

    estimated profit

    Tell students theVice President ofFinancial Services wants

    to view the rounded offaverage profit for the lasteleven years. 2 Switch to Design view If necessary.

    3 Create a new formula field namedAverage profit

    The Formula Workshop Formula Editor Average profit window appears.

    4 In the Formula text window, typethe formula shown:

    The formula uses the Average and Roundfunctions to round off the average profit foreleven years. The formula also combines textand calculations by using the concatenationoperator (&). (Notice that Crystal syntax willignore the line breaks in the code.)

    5 Check the formula, and clickSave and close

    6 Place the new field in the ReportFooter section as indicated

    Increase the width of the field To display all of the text.

    Format the field with Times NewRoman

    7 Preview the report It should look like Exhibit 2-8.

    Update and close the report

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    41/155

    218 Crystal Reports XI: Advanced

    Evaluation Time functions

    Explanation In the process of displaying records, a report goes through three stages:

    1 Before the report reads the records from the database

    2 While the report reads the records from the database

    3 While the report prints the records read from the database

    Each stage is called apass.

    Crystal Reports evaluates the formulas in a report during any one of the passes,depending on the type of formula. Formulas that dont use any database fields areevaluated on the first pass, formulas that use database fields are evaluated during thesecond pass, and formulas that perform calculations on summary fields, such assubtotals, are evaluated during the third pass. When processing records, Crystal ReportsusesEvaluation Time functionsinternally to decide which formula should be evaluatedduring which pass.

    The following table describes the Evaluation Time functions.

    Function Description

    BeforeReadingRecords The formula is executed before the report reads the recordsfrom the database. You cannot use any database field in aformula in which you specify this function.

    WhileReadingRecords The formula is executed for each record as its read from thedatabase.

    WhilePrintingRecords The formula is executed when the report is displaying therecords read from the database. This happens after the reporthas read all the records from the database.

    EvaluateAfter

    ()

    This function takes a formula name as an argument. The

    formula in which you use it will be evaluated after theformula you specify as the EvaluateAfter argument.

    In some situations, you may need to force a formula to be evaluated during a specificpass. To do this, youll need to include an Evaluation Time function in the formula.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    42/155

    Advanced formulas and functions 2

    For example, lets say you have a function that calculates the customer discount andstores it in a variable named DiscountAmount. You also have a function that uses theDiscountAmount variable to calculate the final sales value. In the report, you want todisplay only the final sales value, but because you wont place the discount formula ithe report, its formula wont be evaluated.

    To calculate the finalsales value, youll needto use the EvaluateAfterfunction explicitly in thefinal amount formula byusing the customerdiscount formula as thefunctions argument. Ifyou do, the customerdiscount formula will beevaluated first,producing the variableneeded to calculate thefinal sales value.

    Exhibit 2-9: The formula for calculating salesperson commission

    Do it! C-2: Using the EvaluateAfter function

    Heres how Heres why

    The regionalmanager wants to trackcommissions on all salesfor the region.

    1 Open Commissions This report already has a formula namedCommission that calculates each salespersoncommission. Youll create a formula that willcalculate total remuneration, which is basicsalary ($7000) plus commission.

    2 Save the report as My

    commissions

    View the formula for theCommission formula field

    (In the Field Explorer, expand Formula Fieldsselect Commission, and click the Edit button.)The formula, shown in Exhibit 2-9, calculatescommissions based on a sliding commissionrate.

    Close the Formula Workshopwindow

    Switch to Design view (If necessary.) The Commission formula fieldhas not been placed in the report because only

    the total earnings value needs to be shown.Youll add a formula to calculate the totalearnings for each salesperson; this total is thesum of basic salary and commission.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    43/155

    220 Crystal Reports XI: Advanced

    3 Create a new formula field namedTotal Earnings

    Tell students that theformula field will calculateearnings based on thetotal amounts of the

    products sold, althoughthe salespeoplethemselves do not appearin the report.

    In the Formula text window, enterthe formula shown

    This formula stores the salespersons basicsalary in a variable named Basic. The formulathen declares the variable Commission butdoesnt specify a value because the variableshould refer to the value of the variable with thesame name in the Commission formula. Theformula then calculates the sum of the basicsalary and the commission.

    4 Check the formula, then save itand close the Formula Workshop

    5 Place the Total Earnings field inthe Details section, as shown

    Adjust the alignment of the fieldheading to be consistent with theother headings

    If necessary.

    Remind students todeselect the field.

    6 Preview the report

    The Total Earnings field shows all the values as$7000.00, which is the value of eachsalespersons basic salary. This is because theCommission variable has not been initialized inthis formula, nor has the Commission formulabeen evaluated.

    7 In the Field Explorer, selectTotal Earnings

    (If necessary.) To calculate the correct earningsvalue, youll use the EvaluateAfter function toforce the Commission formula to be evaluated

    before the Total Earnings formula.

    Click To open the Formula Workshop FormulaEditor Total Earnings window.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    44/155

    Advanced formulas and functions 2

    8 Place the insertion point in theindicated position

    Youll enter code above the variabledeclarations.

    Type the following code:

    EvaluateAfter ({@Commission});

    To evaluate the Commission formula before tTotal Earnings formula is evaluated.

    Presse

    9 Observe the formula

    The formula should look like this.

    10 Check the formula, save it, andclose the Formula Workshop

    11 Observe the Total Earningsformula field

    The total earnings as a sum of basic salary andcommission now appears in the formula. Thisbecause the Commission formula is now forceto execute before the Total Earnings formula.

    12 Update and close the report

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    45/155

    222 Crystal Reports XI: Advanced

    Topic D: Constructs

    Explanation You use constructsin a formula to specify which set of steps should be executed andwhen. Constructs, also called control structures, evaluate a condition to decide whetherto execute a set of steps. This process is called looping. The most common constructsare For, While, and If-then-else.

    For constructs

    You use theFor construct when you want to execute a set of steps a certain number oftimes. Use this construct when you know the exact number of times the steps shouldexecute. The syntax is as follows:

    for := to step do

    (steps);

    A For construct uses a countervariableas a looping counter. The value of this variableat any point in time determines whether the steps inside the parentheses will execute.The construct executes in three steps:

    1 It first sets the value of the counter variable to the initial value. This process iscalled initialization.

    2 It then checks whether the value of the counter variable lies between the initialvalue and the final value, inclusively. This is called a conditiontest. If thecondition evaluates to yes, then the loop condition is true. If the conditionevaluates to no, then the loop condition is false. If the condition is true, the

    construct executes the steps between the parentheses following the dokeyword.

    If not, the loop terminates, and the steps after the construct are executed.

    3 It then increases the counter variable by the value specified after the step

    keyword. This value is called an increment.

    Steps 2 and 3 are repeated until the condition test becomes false, or when the value ofthe counter variable exceeds the final value.

    In the For construct syntax, the initialization, condition test, and increment steps areplaced as a single step in the formula.

    For example:

    numberVar i;numberVar j;for i := 1 to 5 step 1 do(j:= j + 2);

    In this example, the formula begins by declaring variables i and j. The loop initializesthe value of i to one (1). The loop will then check whether the value of i lies between 1and 5. If yes, then it will increment j by two. Then the loop will increment the value of i

    by one, as specified after the stepkeyword, and then check the condition again. The

    steps in this For loop will be executed five times.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    46/155

    Advanced formulas and functions 2

    The For construct can terminate in two ways:

    If the condition in the loop becomes false

    If anexit for step is specified in the loop

    Exhibit 2-10: The formula for estimating and displaying profit for the next three year

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    47/155

    224 Crystal Reports XI: Advanced

    Do it! D-1: Using a For construct

    Heres how Heres why

    1 Open Estimated profit 3 years Youll insert a formula in this report to calculatethe estimated profit for the next three yearsbased on a profit rise percentage. Youll use the

    For construct to calculate the estimated profit.

    2 Save the report as Myestimated profit 3 years

    Activate the Design tab If necessary.

    3 Create a new formula namedEstimated profit

    4 In the Formula text window, enterthe formula

    As shown in Exhibit 2-10.The code for this formulacan also be inserted fromthe file Estimated For.txt.

    Observe the first two variabledeclarations

    RisePercent and CurrentYrProfit set values forthe projected percentage of profit increase andthe profits for the current year.

    Observe the Ctr variable This will be the counter in the For construct.

    Observe the next two variabledeclarations

    The RiseInProfit variable will be used tocalculate the projected rise in profit. TheFinalString variable will contain the messagethat the function will ultimately return.

    5 Observe the For construct The Ctr variable is initialized to 1, the steps areexecuted, and then Ctr is increased by the step

    value (1). The construct will execute exactlythree times.

    The steps within the construct calculate eachyears projected profit, and then combine theFinalString message with some space and theprofit value. After the steps execute three times,the FinalString includes all three projected profitvalues.

    Observe the last step in theformula

    This line returns the FinalString value.

    Check the formula, save it, andthen close the Formula Workshop

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    48/155

    Advanced formulas and functions 2

    6 Place the Estimated profit field inthe Report Footer section, asshown

    Format the Estimated profit fieldwith Times New Roman

    Resize the formula field as shown

    7 Preview the report

    To view the estimated profits for all years.

    Remind students todeselect the field.

    Ask students if they canthink of other ways toachieve the same result ina report.

    8 Update the report

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    49/155

    226 Crystal Reports XI: Advanced

    While constructs

    Explanation You use a While construct in situations when you dont know the number of times theloop should execute. This construct executes a set of steps repeatedly while a specifiedcondition is true. In the While construct (unlike in a For construct), the steps forinitialization, condition test, and increment are placed in separate steps. The syntax is asfollows:

    while do(stepsincrement step);

    Its important to put an increment step within the loop. If you dont, the loop will neverend because the value of the counter variable will never change.

    A While construct can terminate in two ways:

    If the condition in the construct becomes false

    If anexit while step is specified in the loop

    Exhibit 2-11: The formula using a While construct

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    50/155

    Advanced formulas and functions 2

    Do it! D-2: Using a While construct

    Heres how Heres why

    1 Switch to Design view

    2 Create a parameter field named

    Profitwhich prompts the user toenter the number of years forwhich to calculate estimated profit

    The data type for the field should be Number.

    3 Place the field in the Page Headersection of the report

    4 Right-click the field and chooseFormat Field

    To open the Format Editor. Youll suppress thfield so that it doesnt appear on the report.

    Activate the Common tab

    Check SuppressTo suppress display of the field in the report.

    Click OK To close the Format Editor.

    5 Edit the formula for the EstimatedProfit field

    As shown in Exhibit 2-11.The code can be insertedfrom the Estimated Whiletext document in thecurrent unit folder.

    6 Observe the While construct (In the formula) The While construct determinthat the steps will be executed as long as thecounter value is less than or equal to theProfitCount value.

    7 Check the formula, save it, and

    close the Formula Workshop

    8 Preview the report A prompt appears directing you to enter thenumber of years for which to calculate estimaprofit

    If a message box appears,tell students to choosePrompt for new parametervalues.

    In the prompt, enter 3 To calculate estimated profit for the next threeyears.

    Click OK To close the prompt and retrieve the records.Profits are estimated for three years.

    If time permits, allowstudents to enter differentvalues in the prompt.

    9 Update and close the report

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    51/155

    228 Crystal Reports XI: Advanced

    Unit summary: Advanced formulas and functions

    Topic A In this topic, you learned about running totals. You learned how to create a runningtotal by using the Create Running Total Field dialog box. You also learned how tomodify a running total, and how to reset a running total based on a change of group.

    Topic B In this topic, you learned that you can use a variableto store a value. Then, you learnedthat you can use an arrayto store multiple values of the same type. You also learnedhow to use a range variableto test whether a value lies between an upper and a lowerlimit.

    Topic C In this topic, you learned how to create formulas by using multiple functions. You alsolearned how to use Evaluation Timefunctions to specify when a formula should beevaluated.

    Topic D In this topic, you learned how to use looping constructs. You learned that you can usethe For constructto execute a set of steps a certain number of times, and you can usethe While constructto execute a set of steps while a certain condition is true.

    Independent practice activity

    In this activity, youll calculate shipping costs by using variables in a formula. Youllalso calculate estimated profits for future years, and insert a running total into a report.

    1 Open Shipping costs from the current unit folder.

    2 Save the report as My shipping costs.

    3 Create a new formula called Shipping costs per sale. The formula should calculatetotal shipping cost for each sale performed. For the formula, declare a numbervariable named shippingcost. Declare a second number variable namedshippingDaysthat equals the Shipping.Delivery date field minus theShipping.Shipping date field. The total shipping cost is calculated as the total

    number of shipping days multiplied by the shipping cost per day. The shipping costsare $50 per day. (The completed code for this formula is in the file Shipping.txt, butfirst try to build it on your own.)

    4 Place the formula after the Delivery date field. Format the field so that itsconsistent with the other fields in the report.

    5 Preview the report and compare it to Exhibit 2-12.

    6 Update and close the report.

    7 Which Evaluation Time function would you use to perform a formula calculationbefore the report reads the records to display from the database?

    BeforeReadingRecords

    8 Which construct would you use to execute a set of steps a known number of times?

    The For construct

    9 Open Estimated sales from the current unit folder.

    10 Save the report as My estimated sales.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    52/155

    Advanced formulas and functions 2

    11 Create a new formula called Estimated sales. Calculate the sales for the next fivyears starting from 2006. Calculate the sales for each year by increasing theprevious years sales by 25%. The sales for 2005 should be taken as the currentyears sales. (The completed code for this is in the file Practice sales.txt, but trybuilding it on your own.) Add the field to the report footer, and then increase thesize to show the contents completely.

    12 Preview the report and compare it to Exhibit 2-13.13 For the year field, insert a running total called Year countthat displays the year

    count on each record. (From the Type of summary list, select count.) Place the fiein the Details section after Sales, format it to match other fields in the report, andcompare it to Exhibit 2-14.

    14 Update and close the report.

    Exhibit 2-12: The report after step 5 of the Independent Practice Activity

    Exhibit 2-13: The report after step 12 of the Independent Practice Activity

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    53/155

    230 Crystal Reports XI: Advanced

    Exhibit 2-14: The report after step 13 of the Independent Practice Activity

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    54/155

    Advanced formulas and functions 2

    Review questions

    1 What calculation would you insert into a report when you want to show incremenincreases in a total?

    Running total

    2 What is a variable?

    An element in a formula that acts as a placeholder for a specific value

    3 When you declarea variable in a formula, you ________________.

    Specify its data type and name

    4 An array variable is a variable that:

    A Stores multiple values of a single data type.

    B Allows you to calculate a running total.

    C Defines a date range.

    D None of the above.

    5 CurrencyVar range sales := 10000 to 50000; is an example of what

    type of variable?

    A range variable

    6 What are the stages, or passes, a report goes through in the process of displayingrecords?

    Before reading records from the database

    While reading records from the database

    While printing records read from the database

    7 What type of function does Crystal Reports use when deciding which formulashould be evaluated during which pass?

    Evaluation Time function

    8 When you know the exact number of times that the steps in a formula shouldexecute, you would use a ______ construct.

    For

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    55/155

    232 Crystal Reports XI: Advanced

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    56/155

    3

    U n i t 3

    Charts and maps

    Unit time: 45 minutes

    Complete this unit, and youll know how to

    A Create and modify charts to provide a

    visual representation of data.

    B Create and customize maps to represent

    data geographically.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    57/155

    32 Crystal Reports XI: Advanced

    Topic A: Working with charts

    Explanation You add charts to a report to provide a visual representation of data. Charts can helpusers interpret and analyze data more effectively than simply viewing a set of records.

    Creating chartsYou can create several types of charts, depending on the type of data you want todisplay. The following table describes some of the available chart types.

    Type Description

    Bar Displays bars of different heights to represent values for sets of data. Use barcharts to display and compare single or multiple sets of data.

    Line Plots data as a series of dots joined by a line. This type of chart is useful foranalyzing trends. For example, you might use a line chart to view profit trendsfor the last 10 years.

    Area Plots data as color-filled areas on the chart. This type of chart is useful forshowing one type of data as a sum of other types. For example, you might wantto show the total costs for a year as the sum of production costs and fixed costs.

    Pie Plots a single set of data, which is represented by divisions of a circle (or slicesof a pie). For example, you could use a pie chart to represent four regions salesas percentages of the total sales.

    Gantt Plots only the date values. The data is represented in a horizontal bar chart. Forexample, you may want to show the schedule of your project.

    Gauge Plots data graphically on a gauge. The data is shown as a set of points and is

    useful for showing only one group of data.

    The Chart Expert

    The Chart Expert, as shown in Exhibit 3-1, has several tabs that guide you through theprocess of creating charts. You use the Chart Expert to specify the type of chart, the datato be plotted, and the chart title, among other things.

    To create a chart:

    1 Choose Insert, Chart to open the Chart Expert.

    2 In the Type tab, select the needed chart type.

    3 Activate the Data tab, and specify the data to be plotted on the chart.4 Activate the Text tab, and specify a chart title.

    5 Click OK to insert the chart.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    58/155

    Charts and maps 3

    Exhibit 3-1: The Chart Expert dialog box

    Exhibit 3-2: The Quantity Sold by State bar chart

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    59/155

    34 Crystal Reports XI: Advanced

    Do it! A-1: Creating a chart

    Heres how Heres why

    1 Open Retailer Information (From the current unit folder.) Youll create achart showing order data.

    2 Save the report as My retailerchart

    Activate the Design tab

    3 Choose Insert, Chart An empty square appears in the report.

    Place the chart in the ReportHeader section, as shown

    Click to place the chart. The section enlarges toaccommodate the size of the chart.

    4 Right-click the chart To display a context menu.

    Choose Chart Expert To open the Chart Expert dialog box. The Typetab is active, and gives you several choices forchart type, as shown in Exhibit 3-1.

    Click on several of the chart types

    in the list

    To see thumbnail images of what the types of

    charts look like.

    5 Select Bar From the chart type list. Youll create a Barchart.

    Verify that below the list of charttypes, the Vertical option isselected.

    The vertical option will create a chart in uprightposition. The Horizontal option changes theorientation of the chart by swapping x and yaxes.

    6 Activate the Datatab Here, youll specify the field values to be plottedon the chart.

    Click as shown

    To view additional options for creating thechart.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    60/155

    Charts and maps 3

    7 From the Available fields list,select Retailers.State

    Click, as shown

    To add the State field to the On change of listThis means that the states will appear on thehorizontal or Group axis of the chart.

    In the drop-down list, the For each record optis used to see values for each record in thereport, whereas the For all records option is uto present a summarized value of all records ithe report.

    8 From the Available fields list,select Orders.Quantity_sold

    The chart will show the sums of values from tQuantity_sold field for each year as one serieon the chart plotted against the vertical or Dataxis.

    Click, as shown

    To add the Quantity_sold field to the Show

    value(s) list.

    9 Activate the Text tab

    On this tab you can specify titles for the entirechart, the axes, and other chart elements. TheAuto-Text option tells the Chart Expert toautomatically assign titles for the elements.

    For the Title box, clear the Auto-Text check box

    Youll replace the auto-text with a custom titl

    Edit the text in the Title box toread Quantity Sold by State

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    61/155

    36 Crystal Reports XI: Advanced

    10 Clear the Auto-Text box for theGroup title

    Edit the Group title box to readStates

    This will be the title for the horizontal axis.

    11 Edit the Data titlebox to readQuantity sold Clear the Auto-Text box and enter the new title.This will be the title for the vertical axis.

    12 Under Format, verify that Title isselected in the list, and click Font

    Youll change the font style of the main title.

    Observe the default font, fontstyle, and size

    The defaults are Arial, Bold, and 13.5.

    13 From the Font style list, chooseBold Italic

    Click OK To close the Font dialog box and apply the new

    style.

    Click OK To close the Chart Expert and apply the newsettings to the chart.

    14 Deselect the chart

    Tell students that inDesign view, the chartdisplays only placeholderdata. It will look different inPreview.

    Preview the report The chart appears as shown in Exhibit 3-2. Itdisplays data for five states, with states plottedon the Group axis, and Quantity sold plotted onthe Data axis.

    Modifying charts

    Explanation After you create a chart, you can modify it by using the Chart Expert, the Chart menu,or both. To modify a chart by using the Chart Expert, select the chart and chooseFormat, Chart Expert. You can then add data points, set the range and scale of thecharts axes, or make any other needed changes.

    Data pointsare small labels that show the actual values plotted on the graph. The rangesets a minimum and maximum limit for the data to be plotted on a chart. For example,you can set the minimum range to 2000 and the maximum range to 4000 if the datavalues to be plotted on the chart range from 2000 to 4000. Using a range will accentuateany trends shown in the chart. The minimum range limit is zero by default. The chartsscale specifies the division of values on the data axes.

    The Chart menu

    Use the Chart menu to format each component of a chart individually. You can also usethe Chart menu to modify chart colors and to save the chart as a template. A templatestores all the formattingsuch as color, scale, and rangethats applied to the chart.You can use the template to create another chart with the same formatting.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    62/155

    Charts and maps 3

    Exhibit 3-3: The Quantity Sold by State chart with data points

    Exhibit 3-4: The chart with modified colors and data points

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    63/155

    38 Crystal Reports XI: Advanced

    Do it! A-2: Modifying a chart

    Heres how Heres why

    1 Activate the Design tab (Youll add data points to your chart to displaythe actual values represented by the chart.)Youll also change the color of the chart to make

    it visually more appealing.

    Select the chart (If necessary.) Youll use the Chart Expert andAnalyzer to modify the chart.

    2 Choose Format,Chart Expert

    (Or right-click the chart and choose ChartExpert from the context menu.) To open theChart Expert dialog box.

    3 Activate the Axes tab

    Under Show gridlines, verify thatMajoris checked corresponding

    to the Data axis

    (To show the gridlines for the data axis on thechart.) You can select Major or Minor to show

    the gridlines for the corresponding axes.

    4 Under Data values, clear Autorange

    Youll modify the data range on the Data axis.The Min, Max, and Number format boxes arenow available.

    In the Min box, enter 1 By raising the minimum of the charts range,you can accentuate the differences between theplotted values.

    In the Max box, enter 2000

    Under Number of divisions, verify

    that Automatic is selected

    To automatically have enough divisions on the

    chart to represent data meaningfully. You canalso select the Manual option and specify thenumber of divisions.

    5 Activate the Options tab

    Under Data points, check Showvalue

    To display the values of the data plotted in thechart.

    Verify that the indicated numberformat is selected

    Verify that Show label is notchecked

    (To ensure that the chart is not too crowded.) Ifyou select this option, the labels correspondingto the data values also appear alongside the datavalues, making the chart appear crowded withtext.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    64/155

    Charts and maps 3

    6 Under Legend, verify that Showlegend is checked and thePlacement is selected as Right

    To ensure that the chart's legend appears. Youcan place the legend to the right, left, or bottoof the chart.

    Click OK To close the Chart Expert dialog box and appthe new settings.

    7 Preview the report All the values now appear as labels by plottedpoints, as shown in Exhibit 3-3.

    Observe the Data axis The scale range now begins at 1, which has theffect of exaggerating the differences betweenthe values in the chart.

    8 Select the chart If necessary.

    Point to a data value, as shown

    The value appears in a screen tip.

    9 Click the NJ bar of the chart (The teal or green area.) To select the plotted data.

    10 Choose Chart, Format SeriesRiser

    To open the Formatting dialog box. Youllchange the color of the selected bar.

    Under Foreground Color, click the

    drop-down arrow

    To open the Color palette.

    Tell students that thecolors are identified inscreen tips by standardcolor values. The colorthey are selecting is 202,255, 171.

    Select the color indicated

    Click OK To close the Format Series Riser dialog box aapply the new color.

    11 Change the TX bar to a pink color Select the TX data point and choose Chart,Format Series Riser. Click the Foreground Coarrow and select the color from the palette; thclick OK.

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    65/155

    310 Crystal Reports XI: Advanced

    12 Select the NJ data point label, asshown

    13 Right-click the label, and choose

    Format Data Label

    To open the Format Data Labels dialog box.

    Youll change the appearance of the labels.

    Click To change the font style to bold.

    From the Size list, select 10 To make the data points appear bold.Point out that theformatting is applied to alldata labels, not only to theselected label.

    Click OK The cost and sale values now appear larger andbold.

    14 Observe the report The chart should look like Exhibit 3-4.Remind students todeselect the chart, ifnecessary.

    15 Update and close the report

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    66/155

    Charts and maps 3

    Funnel charts

    Explanation Funnel charts are useful for depicting data for various stages of a sales process. The dis represented as a percentage of the total of all stages. The individual stage where apotential problem lies is easily identified so you can also use funnel charts to depictother types of data, such as regional distribution of data.

    Funnel charts are similar to the stacked bar charts in that they represent the individuashare in terms of overall total.

    The process to create a funnel chart is similar to creating any other chart. To create afunnel chart:

    1 Choose Insert, Chart to open the Chart Expert.

    2 In the Type tab, select the Funnel chart.

    3 Activate the Data tab, and specify the data to be plotted on the chart.

    4 Activate the Text tab, and specify a chart title.

    5 Click OK to insert the chart.

    A funnel chart appears, as shown in Exhibit 3-5.

    Exhibit 3-5: A funnel chart showing distribution of orders by state

    NOT FOR PRINTING OR INSTRUCTIONAL USE

  • 5/24/2018 Crystal Reports Xi - Advanced 1418861472pv

    67/155

    312 Crystal Reports XI: Advanced

    Do it! A-3: Creating a funnel chart

    Heres how Heres why

    1 Open Retailers Youll make a funnel chart to display theregional distribution of sales.

    2 Save the report asMy retailer funnel

    Activate the Design tab

    3 Insert a new chart in the ReportHeader section

    Choose Insert, Chart and place the chart.

    4 Open the Chart Expert Right-click the chart and choose Chart Expert.

    From the chart type list, selectFunnel

    5 Activate the Data tab Youll specify the data to be plotted.

    Under Data, verify thatRetailers.Stateis selected

    In the second list, verify thatSum of Orders.Quantity_soldis selected

    6 Activate the Options tab

    Under Data points, check

    Show Label

    To display labels for the data points.

    7 Activate the Text tab Youll change the default title of the chart.

    Edit the Title box to readNational OrdersDistribution

    (Clear the Auto-Text box in order to enter thenew title.) You can also give a subtitle and inserta footnote for the funnel chart to make the chartmore i