Chapter 7 - Writing Formulas
Crystal Reports gives you the option to program formulas in either Crystal syntax or Basic syntax. This chapter teaches you how to program with both Basic syntax and Crystal syntax. Dozens of code samples show you exactly how to write code that you can put in your own reports today.
Declaring Report VariablesVariables store a piece of data so that it can be used again within the function. For example, if a calculation is performed multiple times in a formula, then you can store the result in a variable and reference that variable when you need it. This improves performance because you don't have to repeat the calculation. Variables are also used to pass data between formulas and even to sub-reports. By declaring a variable as Global or Shared, it can be used by other functions and sub-reports. If you couldn't share variables, then you would have to duplicate the same calculation in multiple formulas.
To use a variable in a formula, you first have to declare it. This consists of giving it a name and specifying its data type. Declaring a variable follows the format of declaring the variable using the Dim keyword followed by the variable name. Use the As keyword to specify the data type.
Dim var As dataypeCrystal syntax is the opposite of Basic syntax. It lists the variable scope and data type before the variable name.
Local datatype varThe first time a formula is called, all of the variables are automatically assigned their default values. For example, a Number variable is assigned the value 0. See Table 7-1 for a list of the default values for each data type.
Table 7-1. Data Type Default Values
|Basic Data Type||Crystal Data Type||Default Value|
|Date||DateVar||Date(0,0,0) – The Null Date value 00/00/00|
|Time||TimeVar||No default value. Null.|
|DateTime||DateTimeVar||No default value. Null.|
A variable's scope determines which formulas have access to that variable. You can set the scope so that a variable can only be used within the formula it's declared in, or you can make it available to the rest of the report. There are three operators that are used to declare scope:
- Local/Dim: The variable can only be seen within the current formula. The variable is private to that formula and can't be used anywhere else in the report. This is the default scope if you don't specify it.
- Global: The variable can be seen within any formula inside the same report. Sub-reports do not have access to the variable.
- Shared: Similar to Global, but the variable can also be seen within sub-reports.
Dim HireDate As Date
Shared AffiliateCities() As String
|In Crystal syntax, the default scope is Global, not Local. You should be aware of this since this is the exact opposite of how Basic syntax handles the scope when it isn't declared.|
To read all my books online, click here for the Crystal Reports ebooks.