Declaring Variables
Declaring a variable follows the standard format of declaring the variable using the As keyword and then its data type.
Crystal syntax lists the variable scope and data type before the variable name.
Local datatype var
The first time a formula is called, all of the variables are automatically assigned their default values. See Table 8-1 for a list of the default values. Once you declare a variable and assign a value to it, that variable retains its value for the life of the report. Any future calls to that same formula will not initialize the variable back to its default value. This is the opposite of .NET. In .NET, a variable goes out of scope and its memory is released when the function exits. Every time the function is called the variables are automatically reset to their default value.
Crystal doesn’t reset its variables because of the way formulas and report sections work together. Formulas are usually added to sections of a report and a report section is repeatedly entered and exited as records are processed. If a variable lost its value every time a new record is processed, then you wouldn’t be able to track what happened with the last record. Making it easy for variables to retain their values while different records are processed is one reason why Crystal Reports is so powerful. If you want to make sure that a variable is reset to its default value every time, then do so manually.
Table 8-1. Data Type Default Values
Basic Data Type | Crystal Data Type | Default Value |
---|---|---|
Number | NumberVar | 0 |
Currency | CurrencyVar | $0 |
Boolean | BooleanVar | False |
String | StringVar | “” |
Date | DateVar | Date(0,0,0) – The Null Date value00/00/00 |
Time | TimeVar | No default valueNull |
DateTime | DateTimeVar | No default valueNull |
A variable’s scope determines which formulas have access to that variable. There are three operators that you use to declare scope:
Local HireDate As Date
Shared AffiliateCities() As String
An unusual aspect of the Global/Shared variables is that even though their scope says that they can be seen by other formulas, you still have to declare them in each formula that wants to use them. This is unique because in VB .NET if a variable is declared as Public, and another procedure re-declares that variable, then the new variable is created local to the procedure that declared it and the public variable is no longer accessible within the current procedure. When you re-declare the variable in Basic syntax, then that means you now have access to the Global/Shared variable’s memory space. If you don’t re-declare the variable it will give you an error stating that the variable doesn’t exist. So no matter what the scope of a variable is, every formula must declare every variable that it uses.
Variable Assignment
To assign a value constant to a variable use the equal sign.
X = 5
Crystal syntax uses the := for assignment.
X := 5