constant
It's common to find code that contains constant values that recur again and again. You may also find that the code uses hard-to-remember numbers that have no clear meaning.
In these cases, constants can be used to greatly improve the readability and maintainability of the code. Constants are meaningful names that replace numerical values or strings that never change. Although constants are somewhat like variables, they cannot be modified like variables, nor can constants be assigned new values. Constants come from two sources:
1. Internal or system-defined constants are provided by applications and controls. Visual Basic constants are listed in the Visual Basic (VB) and Visual Basic for applications (VBA) object libraries in the "Object Browser". Other applications that provide object libraries, such as Microsoft Excel and Microsoft P Project, also provide lists of constants that can be used with the application's objects, methods, and properties. Constants are also defined in the object library of each ActiveX control. For more information about using the Object Browser, see Chapter 9, "Programming with Objects."
2. Symbolic or user-defined constants are declared using the Const statement. User-defined constants are described in the next section, "Creating your own constants".
In Visual Basic, constant names are in mixed-case format, and their prefix indicates the name of the object library in which the constant is defined. Constants from the Visual Basic and Visual Basic for Applications object libraries begin with vb, such as vbTileHorizontal.
When designing prefixes, you should try your best to prevent accidental conflicts. Constants with the same name but different values should not be present. Even if prefixes are used, two object libraries may still contain the same constants representing different values. In this case, which constant is referenced depends on which object library has higher priority. For information about changing object library priority, see the "References Dialog Box" section.
To be absolutely sure that no constant name conflicts occur, you can qualify references to constants with the following syntax:
[libname.][modulename.]constname
Libname is usually the class name of the control or library. Modulename is the name of the module in which the constant is defined. Constname is a constant name. Each element is defined in the object library and can be viewed in the Object Browser.
Create your own constants
The syntax for declaring constants is :
[Public|Private]Constconstantname[Astype]=expression
The parameter constantname is a valid symbolic name (the rules are the same as those for establishing variable names), and expression consists of a numeric constant or a string constant and an operator; but function calls cannot be used in expression.
The Const statement can represent quantities, dates, and times:
ConstconPi=3.14159265358979
PublicConstconMaxPlanetsAsInteger=9
ConstconReleaseDate=#1/1/95#
String constants can also be defined using the Const statement:
PublicConstconVersion=07.10.A
ConstconCodeName=Enigma
Multiple constant declarations can be placed on one line if separated by commas:
PublicConstconPi=3.14,conMaxPlanets=9,_
conWorldPop=6E 09
The expression to the right of the equal sign (=) is often a number or literal string, but can also be an expression whose result is a number or a string (although the expression cannot contain a function call). You can even define new constants using previously defined constants.
ConstconPi2=conPi*2 Once the constant has been defined, it can be placed in the code to make the code more readable. For example:
StaticSolarSystem(1ToconMaxPlanets)
IfnumPeople>conWorldPopThenExitSub
Set the range of user-defined constants
Like variable declarations, Const statements have scope and use the same rules:
To create a constant that exists only within a procedure, declare the constant inside the procedure.
To create a constant that is valid for all procedures in the module but not for any code outside the module, declare the constant in the declaration section of the module.
To create a constant that is valid throughout your application, declare it in the declaration section of a standard module and place the Public keyword in front of Const. Public constants cannot be declared in a form module or class module.
For more detailed information about scope, see the section "Understanding the Scope of Variables" earlier in this chapter.
Avoid circular references
Because constants can be defined in terms of other constants, care must be taken not to create cycles or circular references between more than two constants. A loop occurs when there are more than two public constants in a program, and each public constant is defined by another. For example:
'In Module1:
PublicConstconA=conB*2 'In the entire application
' is valid in '.
'In Module2:
PublicConstconB=conA/2 'In the entire application
' is valid in '.
If a loop occurs, Visual Basic will generate an error message when trying to run the application. The program cannot be run without resolving the circular reference. To avoid cycles, public constants can be restricted to a single module, or to only a few modules at most.
data type
A variable is a place used to store values. It has a name and a data type. The data type of a variable determines how the bits representing those values are stored in the computer's memory. You can also specify the data type of a variable when declaring it. All variables have a data type to determine what kind of data can be stored.
By default, if the data type is not specified in the declaration, the data type of the variable is Variant. The Variant data type is like a chameleon, it can represent different data types on different occasions. When the specified variable is a Variant variable, there is no need to convert between data types. Visual Basic will automatically complete various necessary conversions.
However, if you know that a variable does always store data of a specific type, and you declare a variable of that specific type, Visual Basic will handle this data more efficiently. For example, a variable that stores a person's name is best represented as a String data type because names always consist of characters.
In addition to variables, data types are also used in other situations. When assigning a value to a property, the value has a data type; the parameters of the function also have a data type. In fact, in Visual Basic, everything related to data is related to data types.
You can also declare an array of any primitive type.
DetailsFor more details, see the "Arrays" section later in this chapter. Chapter 15, "Designing for Performance and Compatibility," also discusses improving application performance by selecting data types.
Declare variables with data types
Before using a non-Variant variable, you must declare the variable as Astype using a Private, Public, Dim, or Static statement. For example, the following statements declare variables of type Integer, Double, String, and Currency respectively:
PrivateIAsInteger
DimAmtAsDouble
StaticYourNameAsString
PublicBillsPaidAsCurrency
A declaration statement can combine multiple declarations, please see the following statement:
PrivateIAsInteger,AmtAsDouble
PrivateYourNameAsString,BillsPaidAsCurrency
PrivateTest,Amount,JAsInteger
Note that if no data type is provided, the specified variable is of the default type. In the above example, the variables Test and Amount are of Variant data type. If your experience with other programming languages has led you to believe that all variables in the same declaration statement have the same specified data type (Integer in this case), then the results here may be refreshing.
Numeric data type
VisualBasic supports several Numeric data types: Integer (integer), Long (long integer), Single (single-precision floating point), Double (double-precision floating point), and Currency (currency). Numeric types generally take up less storage space than Variant types.
If you know that a variable will always store integers (such as 12) rather than numbers with a decimal point (such as 3.57), you should declare it as an Integer or Long type. Integers perform operations faster and take up less memory than other data types. Integer types are particularly useful when used as counter variables within For...Next loops.
For more information about control structures, see "Control Structures Overview" later in this chapter. If the variables contain decimals, they can be declared as Single, Double, or Currency variables. The Currency data type supports 4 digits to the right of the decimal point and 15 digits to the left of the decimal point; it is a precise fixed-point data type suitable for currency calculations. Floating point (Single and Double) numbers have a much larger valid range than Currency, but small carry errors are possible.
Note that floating point values can be represented as mmmEeee or mmmDeee, where mmm is the mantissa and eee is the exponent (raised to the power of base 10). The maximum positive value of the Single data type is 3.402823E 38, or 3.4 times 10 to the power of 38; the maximum positive value of the Double data type is 1.79769313486232D 308, or 1.8 times 10 to the power of 308. Using D to separate the mantissa and exponent parts of a numeric literal causes the value to be treated as a Double data type. Likewise, using E in this way causes the value to be treated as a Single data type.
Byte data type
If the variable contains a binary number, declare it as an array of Byte data type (arrays are discussed in "Arrays" later in this chapter). Storing binary data in Byte variables preserves the data during format conversion. When a String variable is converted between ANSI and Unicode formats, any binary data in the variable will be destroyed. Visual Basic automatically converts between ANSI and Unicode in any of the following situations:
When reading a file
When writing a file
When calling a DLL
When calling methods and properties of an object
Except for unary subtraction, all operators that can operate on integers can operate on the Byte data type. Because Byte is an unsigned type from 0-255, it cannot represent negative numbers. So when doing unary subtraction, VisualBasic first converts the Byte to a signed integer.
All numeric variables can be assigned to each other and to Variant type variables. Before assigning a floating-point number to an integer, Visual Basic rounds the decimal part of the floating-point number instead of removing it.
Details For details about Unicode and ANSI conversion, see Chapter 16, "Internationalization."
String data type
If a variable always contains a string and never a numeric value, you can declare it as type String.
PrivateSAsString
You can then assign a string to this variable and operate on it using string functions.
S=Database
S=Left(S,4)
By default, a String variable or parameter is a variable-length string. As new data is assigned to a string, its length can increase or decrease. It is also possible to declare a string to have a fixed length. A fixed-length string can be declared with the following syntax:
String*size
For example, to declare a 50-character string, use the following statement:
DimEmpNameAsString*50
If less than 50 characters are assigned to the string, the missing portion of EmpName is filled with spaces. If the length assigned to the string is too long and cannot become a fixed-length string, Visual Basic will directly truncate the excess characters.
Because fixed-length strings are filled with spaces at the end of the extra space, the Trim and RTrim functions that remove spaces can be found to be very useful when dealing with fixed-length strings. Fixed-length strings in standard modules can be declared as Public or Private. In forms and class modules, fixed-length strings must be declared Private.
For details, see "Ltrim, RTrim, and Trim Functions" in the "Visual Basic 6.0 Language Reference Manual".
Swap strings and numbers
If the string represents a numeric value, the string can be assigned to a numeric variable. Numeric values can also be assigned to string variables. For example, place command buttons, text boxes, and list boxes on a form. Enter the following code in the Click event of the command button. Run the application and click the command button.
PrivateSubCommand1_Click()
DimintXAsInteger
DimstrYAsString
strY=100.23
intX=strY 'Pass string to numeric variable.
List1.AddItemCos(strY) 'Add the cosine value of the value in the string.
'Add to list box.
strY=Cos(strY) 'Transfer cosine value to string variable.
Text1.Text=strY 'Display string in text box.
EndSub
Visual Basic automatically forces variables to the appropriate data type. Be careful when converting strings and numeric values; if the value in the passed string is not a numeric value, an error will occur at run time.
Boolean data type
If the value of the variable is only "true/false", "yes/no", and "on/off" information, it can be declared as Boolean type. The default value of Boolean is False. In the example below, blnRunning is a Boolean variable that stores a simple yes/no setting.
DimblnRunningAsBoolean
'Check to see if the tape is spinning.
IfRecorder.Direction=1Then
blnRunning=True
Endif
Date data type
Date and Time values can be contained either in the specific Date data type or in Variant variables. General Date properties apply to both types.
For more information, see the "Storing Date/Time Values in Variant Variables" section of the "Advanced Variable Topics" in the Online Manual.
When other numeric data types are converted to Date, the value to the left of the decimal point represents Date information, and the value to the right of the decimal point represents Time. Midnight is 0 and noon is 0.5. Negative numbers represent dates before December 31, 1899 AD.
->