Variables are containers that hold values. OpenOffice.org supports different types of variables designed to hold different types of values. This section shows how to create, name , and use variables. Although OOo Basic does not force you to declare variables, you should declare every variable that you use. The reasons for this are developed throughout this section.
Always choose meaningful names for your variables. Although the variable name 'Varl" requires little thought during creation, "FirstName" is more meaningful. Some variable names are not particularly descriptive but are commonly used by programmers anyway. For example, "i" is commonly used as a shortened version of "index," for a variable that is used to count the number of times a repetitive task is executed in a loop. OOo Basic imposes restrictions on variable names, including the following:
A variable name cannot exceed 255 characters in length. Well, officially a variable name cannot exceed 255 characters. I tested names with more than 300 characters with no problems, but I don't recommend this.
The first character of a variable name must be a letter: A-Z or a-z.
The numbers 0-9 and the underscore character (_) may be used in a variable name, but not as the first character. If a variable name ends with an underscore , it won't be mistaken for a line-continuation character.
Variable names are not case sensitive, so "FirstName" and "firstNAME" both refer to the same variable.
Variable names may contain spaces but must be enclosed in square brackets if they do. For example, [First Name]. Although this is allowed, it is considered poor programming practice.
Note | These restrictions also apply to constant, subroutine, function, and label names. |
Some programming languages require that you explicitly list all variables used. This process is called "declaring variables." OOo Basic does not require this. You are free to use variables without declaring them.
Although it is convenient to use variables without declaring them, it is error-prone . If you mistype a variable name, it becomes a new variable rather than raising an error. Place the keywords "Option Explicit" before any runnable code to cause OOo Basic to treat undeclared variables as run-time errors (see Listing 6 ). Comments may precede Option Explicit because they are not runnable. Although it would be even better if this became a compile-time error, OOo Basic does not resolve all variables and routines until run time.
REM ***** BASIC ***** Option Explicit
Tip | Use "Option Explicit" at the top of every macro that you write; it will save you a lot of time searching for errors in your code. When I am asked to debug a macro, the first thing I do is add "Option Explicit" at the top of each module. |
You can declare a variable with or without a type. A variable without an explicit type becomes a Variant, which is able to take on any type. This means that you can use a Variant to hold a numeric value and then, in the next line of code, overwrite the number with text. Table 1 shows the variable types supported by OOo Basic, the value that each type of variable contains immediately after declaration ("initial value"), and the number of bytes that each type uses.
Type | Initial Value | Bytes | Description |
---|---|---|---|
Boolean | False | 1 | True or False |
Currency | 0.0000 | 8 | Currency with 4 decimal places |
Date | 00:00:00 | 8 | Dates and times |
Double | 0.0 | 8 | Decimal numbers in the range of +/- 1.79769313486232x 10E308 |
Integer |
| 2 | Integer from -32,768 through 32,767 |
Long |
| 4 | Integer from -2147483648 through 2147483647 |
Object | Null | varies | Object |
Single | 0.0 | 4 | Decimal numbers in the range of +/- 3.402823x 10E38 |
String | Zero-length string | varies | Text with up to 65536 characters |
Variant | Empty | varies | May contain any data type |
Bug | Although OOo Basic supports a Byte variable type, you can't directly declare and use one. The function CByte, as discussed later, returns a Byte value that may be assigned to a variable of type Variant. |
Use the DIM keyword to explicitly declare a variable before use (see Table 2 ). You can declare multiple variables on a single line, and you can give each variable a type when it is declared. Variables with no declared type default to type Variant.
Declaration | Description |
---|---|
Dim Name | Name is type Variant because no type is stated. |
Dim Name As String | Name is type String because the type is explicitly stated. |
Dim Name$ | Name$ is type String because Name$ ends with a $. |
Dim Name As String, Weight As Single | Name is type String and Weight is type Single. |
Dim Width, Length | Width and Length are type Variant. |
Dim Weight, Height As Single | Weight is type Variant and Height is type Single. |
Warning | When multiple variables are declared in a single line, the type for each variable must be listed separately. In the last line of Table 2, Weight is a Variant, even if though it looks like it may be of type Single. |
Much of the available literature on OOo macro programming uses a variable naming scheme based on Hungarian notation. With Hungarian notation, you can determine a variable's type from its name. In practice, everyone does this differently and with differing levels of adherence. This is purely a stylistic decision that some people love and some people hate.
OOo Basic uses Def<type> statements to facilitate the use of Hungarian notion. The Def statements, which are local to each module that uses them, provide a default type for an undeclared variable based on its name. Normally, all undeclared variables are of type Variant.
The Def statement is followed by a comma-separated list of character ranges that specify the starting characters (see Listing 7 ).
DefInt i-k,n
Table 3 contains an example of each supported Def statement. Def statements, like Option statements, are placed in the module before any runnable line or variable declaration. The Def statement does not force a variable with a specific first letter to be of a certain type, but rather provides a default type other than Variant for variables that are used but not declared.
Def Statement | Type |
---|---|
DefBool b | Boolean |
DefDate t | Date |
DebDbl d | Double |
Deflnt i | Integer |
DefLng l | Long |
DefObj o | Object |
DefVar v | Variant |
Tip | If you use "Option Explicit," and you should, you must declare all variables. This renders the Def<type> statements useless because they affect only undeclared variables. |
Compatibility | Visual Basic .NET does not support the commands in Table 3. |
I have never seen the Def statements used-probably because it is considered bad programming practice to use variables without declaring them. Def statements would be more useful if they provided default types for declared variables with no declared type.
The purpose of a variable is to hold values. To assign a value to a variable, type the name of the variable, optional spaces, an equals sign, optional spaces, and the value to assign to the variable, like so:
X = 3.141592654 y = 6
The optional keyword Let may precede the variable name but serves no purpose other than readability. A similar optional keyword, Set, meant for Object variables, serves no purpose other than readability. These keywords are rarely used.
Compatibility | Visual Basic .NET does not support the keywords Set and Let. |
Boolean variables are able to store only two values: True or False. They are internally represented by the Integer values -1 and 0, respectively. Any numeric value assigned to a Boolean that does not precisely evaluate to 0 is converted to True.
Bug |
Sub ExampleBooleanType Dim b as Boolean b = True b = False b = (5 = 3) REM Set to False Print b REM Print False b = (5 < 7) REM Set to True Print b REM Print True b = 7 REM Set to True because 7 is not 0 End Sub
Note | The internal binary representation of True as -1 has all of the bits set to 1. The internal binary representation of False as 0 has all of the bits set to 0. (Geek Note: The internal binary representations of these numeric values are equal to the standard two's-complement representations of those Integer values. This internal consistency is quite satisfying to those who think about such things.) |
Numeric variables, as the name implies, contain numbers. OOo Basic supports integers, floating-point, and currency numbers. Integers may be expressed as hexadecimal (base 16), octal (base 8), or the default decimal numbers (base 10). In common practice, OOo users almost always use decimal numbers, but the other types are presented here as well, for completeness.
Decimal numbers, base 10, are composed of the 10 digits 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. Add 1 to 9 in decimal and the result is 10. Binary (base 2), octal (base 8), and hexadecimal (base 16) numbers are also commonly used in computing. Octal numbers are composed of the numbers 0, 1, 2, 3, 4, 5, 6, and 7. In octal, add 1 to 7 and the result is 10 (base 8). Hexadecimal numbers are composed of the 16 digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F. Binary numbers are composed of the two digits 0 and 1. Table 4 contains the numbers from 0 through 18 in decimal, and their corresponding values in binary, octal, and hexadecimal bases.
Decimal | Binary | Octal | Hexadecimal |
---|---|---|---|
|
|
|
|
1 | 1 | 1 | 1 |
2 | 10 | 2 | 2 |
3 | 11 | 3 | 3 |
4 | 100 | 4 | 4 |
5 | 101 | 5 | 5 |
6 | 110 | 6 | 6 |
7 | 111 | 7 | 7 |
8 | 1000 | 10 | 8 |
9 | 1001 | 11 | 9 |
10 | 1010 | 12 | A |
11 | 1011 | 13 | B |
12 | 1100 | 14 | C |
13 | 1101 | 15 | D |
14 | 1110 | 16 | E |
15 | 1111 | 17 | F |
16 | 10000 | 20 | 10 |
17 | 10001 | 21 | 11 |
18 | 10010 | 22 | 12 |
It is common to state how much memory a data type uses in terms of the number of bits or bytes. For example, a 4-bit number can be used to express all the numbers from 0 through 15 (see Table 4). There are eight bits in a byte, so it is easy to convert between the number of bits and the number of bytes. A byte can express the same range of numerical values as 8 bits, as two hexadecimal digits (00 through FF), or as counting from 0 to 255 in decimal. Different number base systems are used to express values for different purposes; OOo Basic can be more easily applied to more situations because we can express numerical values in different bases.
Note | A discussion of other number bases is important because internally, computers represent their data in binary format. It is easy to convert between the binary, hexadecimal, and octal number bases; and for humans it is typically easier to visualize binary numbers when represented in other number bases. |
Integers are assumed to be expressed as decimal numbers. Commas are not allowed. Hexadecimal numbers are preceded by "&H" and octal numbers are preceded by "&O" (letter O, not a zero). Unfortunately, there is no easy method to enter binary numbers. Table 5 presents a few simple guidelines for entering numbers.
Example | Description |
---|---|
Use 1000 not 1,000 | Write numbers without a thousands separator; do not use commas. |
+ 1000 | A space is permitted between a leading plus or minus sign and the number. |
&HFE is the same as 254 | Precede a hexadecimal number with &H. |
&O11 is the same as 9 | Precede an octal number with &O. |
Use 3.1415 not 3,1415 | Do not use commas for the decimal. |
6.022E23 | In scientific notation, the "e" can be uppercase or lowercase. |
Use 6.6e-34 not 6.6e -34 | Spaces are not allowed in a number. With the space, this evaluates as 6.6 - 34 = -27.4. |
6.022e+23 | The exponent may contain a leading plus or minus sign. |
1.1e2.2 evaluates as 1.1e2 | The exponent must be an integer. The fractional portion is ignored. |
Warning | Assigning a String to a numeric variable sets the variable to zero and does not generate an error. |
An integer is a whole number that may be positive, negative, or equal to zero. Integer variables are a good choice for numbers representing non-fractional quantities , such as age or number of children. In OOo Basic, Integer variables are 16-bit numbers supporting a range from -32768 through 32767. Floating-point numbers assigned to an integer are rounded to the nearest Integer value. Appending a variable name with "%" when it is declared is a shortcut to declaring it as type Integer (see Listing 9 ).
Sub ExamplelntegerType Dim il As Integer, i2% REM i1 and i2 are both Integer variables Dim f2 As Double f2= 3.5 i1= f2 REM i1 is rounded to 4 Print i1 REM 4 f2= 3.49 i2= f2 REM i2 is rounded to 3 Print i2 REM 3 End Sub
"Long" is an integer type that has a greater range than type Integer. Long variables are 32-bit numbers supporting a range from -2,147,483,648 through 2,147,483,647. Long variables use twice as much memory as Integer variables but they can hold numbers that are much larger in magnitude. Floating-point numbers assigned to type Integer are rounded to the nearest Integer value. Appending a variable name with "&" when it is declared is a shortcut to declaring it as type Long (see Listing 10 ).
Sub ExampleLongType Dim NumberOfDogs&, NumberOfCats As Long ' Both variables are Long Dim f2 As Double f2= 3.5 NumberOfDogs= f2 REM round to 4 Print NumberOfDogs REM 4 f2= 3.49 NumberOfCats= f2 REM round to 3 Print NumberOfCats REM 3 End Sub
Tip | Historically, operations on Integer variables took less time to run than operations on Long variables. With newer computers, this is not always true. If the run time is significant and you can use either type, test both types to see which is faster. |
Currency variables, as the name implies, are designed to hold financial information. Currency variables are 64-bit, fixed-precision numbers. Calculations are done to four decimal places and 15 nondecimal digits accuracy. This yields a range from -922,337,203,658,477.5808 through +922,337,203,658,477.5807. Appending a variable name with "@" when it is declared is a shortcut to declaring it as type Currency (see Listing 11 ).
Sub ExampleCurrencyType Dim Income@, CostPerDog As Currency Income@ = 22134.37 CostPerDog = 100.0 / 3.0 REM Prints as 22134.3700 Print "Income = " & Income@ REM Prints as 33.333 Print "Cost Per dog = " & CostPerDog End Sub
Note | The Currency type was originally introduced to avoid the rounding behavior of the floating-point types Single and Double. |
Compatibility | Visual Basic .NET removed the Currency type in favor of the Decimal type. |
Single variables, unlike Integer variables, can have a fractional portion. They are called "floating-point numbers" because, unlike Currency variables, the number of decimals allowed is not fixed. Single variables are 32-bit numbers that are accurate to about seven displayed digits, making them suitable for mathematical operations of average precision. They support positive or negative values from 3.402823 x 10E38 to 1.401298 x 10E-45. Any number smaller in magnitude than 1.401298 x 10E-45 becomes zero. Appending a variable name with "!" when it is declared is a shortcut to declaring it as type Single (see Listing 12 ).
Sub ExampleSingleType Dim GallonsUsed As Single, Miles As Single, mpg! GallonsUsed = 17.3 Miles = 542.9 mpg! = Miles / GallonsUsed Print "Fuel efficiency = " & mpg! End Sub
Double variables are similar to Single variables except that they use 64 bits and have about 15 significant digits. They are suitable for high-precision mathematical operations. Double variables support positive or negative values from 1.79769313486232 x 10E308 to 4.94065645841247 x 10E-324. Any number smaller in magnitude than 4.94065645841247 x 10E-324 becomes zero. Appending a variable with "#" when it is declared is a shortcut to declaring it as type Double (see Listing 13 ).
Sub ExampleDoubleType Dim GallonsUsed As Double, Miles As Double, mpg# GallonsUsed = 17.3 Miles = 542.9 mpg# = Miles / GallonsUsed Print "Fuel efficiency = " & mpg# End Sub
String variables are used to hold text. In OOo, text is stored as Unicode version 2.0 values, which provides good support for multiple languages. Each String variable can hold up to 65,535 characters. Appending a variable with "$' when it is declared is a shortcut to declaring it as type String (see Listing 14 ).
Sub ExampleStringType Dim FirstName As String, LastName$ FirstName = "Andrew" LastName$ = "Pitonyak" Print "Hello " & FirstName & " " & LastName$ End Sub
Note | The Unicode Worldwide Character Standard is a set of binary codes representing text or script characters designed because ASCII could handle only 255 distinct characters, thereby making it difficult to handle text in multiple languages. The current Unicode standard contains more than 34,000 distinct coded characters taken from 24 supported language scripts. |
Always remember that in OpenOffice.org, String variables are limited to 65,535 characters. I saw a macro that counted the number of characters in an OpenOffice.org text document by first converting the entire document to a string. The macro worked until the document contained more than 65,535 characters.
Compatibility | In Visual Basic .NET, String variables may contain approximately 2 billion Unicode characters. String variables in OOo Basic are limited to 65,535 Unicode characters. |
OOo 1.1.0 doesn't easily support embedding double quotation marks into a string. OOo 2.0 is scheduled to interpret two adjacent double quotation marks inside a string as a single double quotation mark inserted into the string; this sounds complicated but it is really very simple. To insert a double quotation character into a string, place two double quotation characters into the string, like so:
S = "She said ""Hello""" REM She said "Hello"
Another new feature scheduled for OOo 2.0 is support for Visual Basic string constants when "Option Compatible" is used (see Table 6 ).
Constant | Value | Description |
---|---|---|
vbCr | CHR$(13) | Carriage return |
vbCrLf | CHR$(13) & CHR$(10) | Carriage return/ linefeed combination |
vbFormFeed | CHR$(12) | Form feed |
vbLf | CHR$(10) | Line feed |
vbNewLine | CHR$(13) & CHR$(10) or CHR$(10) | Platform-specific newline character- whatever is appropriate |
vbNullChar | CHR$(0) | Character with ASCII value 0 |
vbNullString | String with value 0. Not the same as a zero-length string (""); in some programming languages this might be called a null string. | |
vbTab | CHR$(9) | Horizontal tab |
vbVerticalTab | CHR$(11) | Vertical tab |
The string constants in Table 6 allow you to define constant strings with special characters. Previously, you had to define the string by using code that called the CHR$() function.
Const sGreeting As String = "Hello" & vbCr & "Johnny" ' This contains a CR.
Date variables contain date and time values. OOo Basic stores dates internally as a Double. Dates, like all numerical types, are initialized to zero, which corresponds to December 30, 1899 at 00:00:00. Adding or subtracting 1 to/from a date corresponds to adding or subtracting a day. One hour , one minute, and one second correspond to the numbers 1/24, 1/(24 * 60), and 1/(24 * 60 * 60), respectively. See Listing 15 . The date functions supported by OOo Basic are introduced in Table 7 and fully discussed later.
Function | Type | Description |
---|---|---|
CDate(expression) | Date | Convert a number or string to a date. |
CDateFromlso | Date | Convert to a date from an ISO 8601 date representation. |
CDateTolso | Date | Convert a date to an ISO 8601 date representation. |
Date | Date | Return the current date as a String. |
DateSerial(yr, mnth, day) | Date | Create a date from component pieces: Year, Month, Day. |
DateValue(date) | Date | Extract the date from a date/time value by truncating the decimal portion. |
Day(date) | Date | Return the day as an Integer from a Date value. |
GetSystemTicks | Date | Return the number of system ticks as a Long. |
Hour(date) | Date | Return the hour as an Integer from a Date value. |
IsDate | Date | Is this a date? |
Minute(date) | Date | Return the minute as an Integer from a Date value. |
Month(date) | Date | Return the month as an Integer from a Date value. |
Now | Date | Return the current date and time as a Date object. |
Second(date) | Date | Return the seconds as an Integer from a Date value. |
Time | Date | Return the time as a String. |
Timer() | Date | Return the number of seconds since midnight as a Date. Convert to a Long. |
TimeSerial(hour, min, sec) | Date | Create a date from component pieces: Hours, Minutes, Seconds. |
WeekDay(date) | Date | Return the integer 1 through 7, corresponding to Sunday through Saturday. |
Year(date) | Date | Return the year as an Integer from a Date value. |
Sub ExampleDateType Dim tNow As Date, tToday As Date Dim tBirthDay As Date tNow = Now() tToday = Date() tBirthDay = DateSerial(1776, 7, 4) Print "Today = " & tToday Print "Now = " & tNow Print "A total of " & (tToday - tBirthDay) &_ " days have passed since " & tBirthDay End Sub
Negative numbers are valid and correspond to dates before December 30, 1899. January 1, 0001, corresponds to the floating-point number -693,595. Continuing backward produces dates that are B.C. (Before Christ, sometimes also referred to as B.C.E., meaning Before the Christian Era, or Before the Common Era) rather than A.D. (Anno Domini). A thorough discussion of date handling is presented later.
In most implementations of the BASIC programming language, you can create your own data types (see Listing 16 ). OOo Basic allows you to define your own data types, and as of version 1.1.1 you can finally use them-in previous versions, you could define your own types but you couldn't use them.
Type PersonType FirstName As String LastName As String End Type Sub ExampleCreateNewType Dim Person As PersonType Person.FirstName = "Andrew" Person.LastName = "Pitonyak" PrintPerson(Person) End Sub Sub PrintPerson(x) Print "Person = " & x.FirstName & " " & x.LastName End Sub
Note | As of version 1.1.1, user -defined types cannot contain an array. |
There are some OOo-defined types that act like user-defined types-for example, the type "com.sun.star.beans.PropertyValue":
Dim oProp As New com.sun.star.beans.PropertyValue
The actual type name of the object is "com.sun.star.beans.PropertyValue". Many of the objects in OOo have similar, long, cumbersome names. While writing about or discussing variable types such as this, it's common to abbreviate the type name as the last portion of the name-in this case, "PropertyValue". Objects of type PropertyValue have two properties: Name as a String and Value as a Variant.
Dim oProp As New com.sun.star.beans.PropertyValue oProp.Name = "Age" 'Set Name Property oProp.Value = 27 'Set Value Property
Most variables copy by value. This means that when I assign one variable to another, the value from one is placed into the other. They do not reference the same data; they contain their own copy of the data. This is also true of these user-defined types. Variables that can be defined in this way are copied by value. Other types used internally by OOo, called Universal Network Objects, are copied by reference. Although these are discussed thoroughly later, it is important to start thinking about what happens when one variable is assigned to another. If I assign one variable to another and it is copied by reference, then both variables refer to the same data. If two variables refer to the same data, and if I change one variable, then I change another. This is similar to what happens when a variable is passed to a routine and it is not passed by value.
In OOo 1.1.0, you can use the keywords "As New" to define a variable as a known UNO struct (see following Note). OOo 2.0 is scheduled to support a new syntax to define variables of known and unknown types. The new syntax and usage requires the use of "Option Compatible." A simple example is declaring a variable of a specific type even if the type is not known to OOo Basic.
Note | The word "struct" is an abreviated form of the word "structure" that is frequently used by computer programmers. A struct has one or more data members , each of which may have different types. Structs are used to group associated data together. |
Option Compatible 'Not yet supported in OOo 1.1.1 Sub Main Dim oVar1 As Object Dim oVar2 As MyType Set oVar1 = New MyType 'Not yet supported in OOo 1.1.1 Set oVar2 = New MyType 'Not yet supported in OOo 1.1.1 Set oVar2 = New YourType 'Error, declared as MyType not YourType.
A new OLE object factory will be introduced with OOo 2.0, which will allow new types to be created. The new functionality should even allow OOo Basic to manipulate Microsoft Word documents on Microsoft Windows operating systems if Microsoft Office is also installed on the computer.
Sub Main Dim W As Word.Application Set W = New Word.Application REM Dim W As New Word.Application 'This should also work in 2.0 REM W = CreateObject("Word.Application") 'This should also work in 2.0 W.Visible = True End Sub
The use of CreateObject() does not rely on "Option Compatible" because this functionality is provided by the new OLE object factory that is scheduled to be released with OOo 2.0.
Warning | Remember that statements such as "will be introduced in OOo 2.0" means that I believe that it is true, but it may not ever happen. The information was publicly released to the mailing list dev@api.openoffice.org by a project lead at Sun Microsystems. |
An Object is a complex data type that can contain more than a single piece of data. The code in Listing 16 shows an example of a complex data type. In OpenOffice.org, Object variables are intended to hold complex data types created and defined by OOo Basic. When a variable of type Object is first declared, it contains the special value Null, which indicates that no valid value is present.
Warning | Use the Variant type, not Object, to refer to OpenOffice.org internals. This is discussed later. |
Compatibility | Visual Basic .NET does not support the keyword Null; it uses the DbNull type instead. |
Variant variables are able to hold any data type. They take on the type of whatever is assigned to them. When a variable of type Variant is first declared, it contains the special value Empty, which indicates that no value has been assigned to the variable. A Variant may be assigned an integer in one statement and then assigned text in the next. No typecasting occurs when assigning data to a Variant; it simply becomes the appropriate type.
The chameleon-like behavior of Variant variables allows them to be used as any other variable type. However, this flexibility comes with a cost: time. One final problem is that it isn't always obvious what type a Variant will become after making some assignments (see Listing 17 and Figure 1 ). It is more efficient, both in time and space- and often in debugging time!-to use the correct variable type.
Sub ExampleTestVariants DIM s As String DIM v As Variant REM v starts Empty s = s & "1 : TypeName = " & TypeName(v) & " Value = " & v & CHR$(10) REM v becomes a String v= "ab217" s = s & "2 : TypeName = " & TypeName(v) & " Value = " & v & CHR$(10) REM v becomes a Boolean v= True s = s & "3 : TypeName = " & TypeName(v) & " Value = " & v & CHR$(10) REM v becomes an Integer rather than a Boolean v= (5=5) s = s & "4 : TypeName = " & TypeName(v) & " Value = " & v & CHR$(10) REM Double v= 123.456 s = s & "5 : TypeName = " & TypeName(v) & " Value = " & v & CHR$(10) REM Integer v=123 s = s & "6 : TypeName = " & TypeName(v) & " Value = " & v & CHR$(10) REM This could be a Long but it turns into a Double v= 1217568942 s = s & "7 : TypeName = " & TypeName(v) & " Value = " & v & CHR$(10) MsgBox s, 0, "The Variant Takes Many Types" End Sub
Compatibility | Visual Basic .NET does not support type Variant. Undeclared variables are of type Object. |
When data is assigned to a Variant, the data is not converted to an appropriate type, but rather the Variant becomes the type of the data. In line 6 of Figure 1, the Variant is an Integer. In line 7, the number is too large to be an Integer, but it is small enough to be a Long. OOo Basic chooses to convert whole numbers larger than an integer and all floating-point numbers into a Double, even if they can be expressed as a Single or a Long.
A constant is like a variable that does not change. It has no specific type. The variable is defined to be a placeholder that is substituted for the expression that defines the constant. Constants are defined with the keyword Const. The constant name can be any valid variable name.
Const ConstName=Expression
Constants improve macros in many ways. Consider a Gravity constant frequently used in physics. Physics scholars will recognize this as the acceleration due to gravity in meters per second squared.
Const Gravity = 9.81
Here are some specific benefits of using constants:
Constants improve the readability of a macro. The word Gravity is easier to recognize than the value 9.81.
Constants are easy to manage. If I require greater precision or if the gravitational pull changes, I only have to change the value in one location.
Constants help prevent difficult-to-find errors by changing run-time errors into compile-time errors. Typing "Gravity" rather than "Gravity" is a compile-time error, while mistyping "9.81" as "9.18" is not.
While a value like 9.81 may be obvious to you, it may not be as obvious to others reading your code later. It becomes what programmers call a "magic number," and experienced programmers try to avoid magic numbers at all costs. Their unexplained meanings make for difficulties in maintaining code later, when the original programmer is not available to explain-or has forgotten the details entirely.
Note | OpenOffice.org defines the constant Pi. This is a mathematical constant with a value of approximately 3.1415926535897932385. |