Crystal Reports - Creating Variables



A Variable is used to assign different values to an object unlike constant which is fixed. When you assign a value to a variable, it maintains that value till you assign a new value to it. Before using variables, it is necessary to define them in a report.

When you declare a variable in Crystal Report you need to assign a name to it, however this name shouldn’t be the same as any other function, operator, etc. A variable can be a number type, string type, date type, Boolean type, range type or an array type. A variable can hold a value of single type, like if you declare it as a number it can’t be used to hold string values later.

Defining a Variable

Local Stringvar Customer_Lastname
Local numbervar Sales_percentage

The keyword for declaring the variable has ‘var’ at the end and it is true for all variable types. You can also assign an initial value to a variable with declaration or in separate syntax.

Local NumberVar Z; //Declare Z to be a Number variable
Z := 30;           //Assign the value of 30 to Z

To use Variables in formulas, its scope is defined. Variable scope can be of three types −

  • Local
  • Global
  • Shared

This defines that a variable in one formula can be used in other formula.

Local Variables

Local variables are declared using the local keyword followed by the type and followed by the variable name as in the above examples.

Local variables are restricted to a single formula. This means that you cannot access the value of a local variable in one formula from a different formula.

//Formula 1
Local NumberVar Z;
Z := 30;

//Formula 2
EvaluateAfter ({@Formula A})
Local NumberVar Z;
Z := z + 5;

In the above example, Formula 2 will return a value 5 as Z is declared as local number variable in formula 1 so it will take default value for variable Z in formula 2.

Global Variables

Global variables are used throughout the main report. Their value is available to all formulas that declare the variable, except for those in sub reports.

Global StringVar Z;

It is recommended that you use global variable only when local variables do not suffice.

Since global variables share their values throughout the main report, you cannot declare a global variable in one formula with one type and then declare a global variable with the same name in a different formula with a different type.

Shared Variables

Shared variables are used throughout the main report and all of its sub reports. Shared variables are even more general than global variables.

To use a shared variable, declare it in a formula in the main report −

Shared NumberVar Z := 10;

To use shared variables, it must be declared and assigned a value before it can be used in the main report and subreports.

Advertisements