Declaration Modifiers

This final section discusses several features of the Visual Basic language that influence the use of declaration throughout portions of code, whole modules, even an entire application.

Global Options

The Declarations section of a module is the home to several important elements of a Visual Basic project. Of course, module-level and global variables and constants are found in this section, as well as user-defined data type definitions. In addition to these elements, there are several options that can be set. This section describes these options.

DEFTYPE

The DefType statements include DefBool, DefByte, DefCur, DefDate, DefDbl, Def-Dec, DefInt, DefLng, DefObj, DefSng, DefStr, and DefVar. These statements allow you to indicate that variables starting with a specific letter are automatically assigned to a specific data type. Procedure arguments and return values from functions and Property Get routines are also affected by these statements. For example, the statement

DefBool a-c

sets all affected elements within the module that begin with the letters a, b, or c, to the data type Boolean, unless an element is specifically typed with an As clause.

The DefType statements must not be used within a Visual Basic application. Allowing variables to be declared without As clauses permits subtle data type errors to appear, especially within medium to large Visual Basic applications.

VBScript does not use the DefType statements since the only non-object data type is Variant.

OPTION BASE

Option base is used to set the default lower bound for array subscripts to either 0 or 1. For example, the statement

Option Base 0

indicates that all arrays declared without the To clause have a lower bound of 0. A declaration of

Dim asName(5)

is the same as

Dim asName(0 To 5)

The default setting in the absence of the Option Base statement is to set the lower bound of arrays to 0.

Do not use the Option Base statement within Visual Basic. Instead, always specify the lower and upper bounds for all arrays (where subscripts are indicated at all) when they are declared with the Dim or ReDim statements.

Incorrect

Dim asNames(5, 10)

Correct

Dim asNames(1 To 5, 1 To 10)

OPTION COMPARE

The Option Compare statement specifies the sorting order for text during comparisons. The two settings, Binary and Text (the Microsoft Access version of VBA adds a Database setting), use different rules for sorting upper-case, lower-case, international, and accented characters. The default setting is Binary.

Use the Option Compare statement as needed within your application. If you choose to use it within one module, add the statement to the Declarations section of all modules. If your application makes certain assumptions about the sorting order of text, be sure to provide adequate documentation within those procedures where it makes a difference, and also within the application's Resource Kit. Some Visual Basic features, such as the InStr() function, contain arguments used to override the default comparison setting.

OPTION EXPLICIT

The Option Explicit statement requires all variables and constants used within a Visual Basic module to be declared before use. In the absence of this statement, it is possible to use variables and constants without first declaring them. The Option Explicit statement must appear as the first non-comment line of each module within your Visual Basic application. This rule also applies to VBScript pages and files.

OPTION PRIVATE MODULE

The Option Private Module statement is used within some implementations of Visual Basic for Applications to restrict the view of public module-level elements to the project in which the module appears. Use the Option Private Module statement as needed within your Visual Basic for Applications code.

Compiler Directives

Visual Basic 4.0 introduced compiler directives into the language. These statements, which always begin with the number sign ("#"), direct the Visual Basic compiler or interpreter to alter the way it processes certain sections of code. Similar directives exist in the C and C++ languages, where they are intercepted by a "pre-processor," which acts on the source code before it is seen by the real compiler.

#CONST DIRECTIVE

The #Const directive defines a compiler constant, a non-changing value for use only with other compiler directives. Visual Basic does define a few global compiler directives, but you are free to define as many as you need.

Use #Const directives as needed to define compiler constants within your application. #Const directives should always appear in the Declarations section of a module. (Even if they appear within a routine, Visual Basic interprets them as if they appeared in the Declarations section.) Like standard constants, values defined with the #Const directive should be all upper case, with underscore characters ("_") separating the key words of the constant.

Correct

#Const DEBUG_VERSION = 1

It is possible to define global compiler constants through the Project Properties dialog in the Visual Basic development environment. Document all custom compiler constants used in your application in the project's Resource Kit.

#IF, #ELSE, #ELSEIF, #END IF DIRECTIVES

The #If directive and related directives allow you to exclude Visual Basic source code from the view of the compiler or interpreter based on the values of compiler constants. Use the #If directive and related directives as needed to direct the inclusion or exclusion of code sections within your application.

Visual Basic Limitations on Declaration

Visual Basic does impose some maximum limits on the number of allowed object names through its use of the Project Name Table. This table, managed internally by Visual Basic, contains the names of all variables, procedures, constants, modules, types, and so on. The Visual Basic Programmer's Guide has this to say about the Project Name Table.

The project name table is unlimited in total size, but is limited to a total of 32K case-sensitive unique entries. If the limit is reached, reuse private identifiers in different modules to limit the number of unique entries to 32K.

This means that the total length of all object names in your application, including some overhead, cannot exceed 32K. For most small and medium-sized projects this is not a problem. But large projects, especially those that have a large number of user-defined constants from third-party vendors, can quickly reach the limit. Although it was written for use with Visual Basic 3.0, Microsoft Knowledge Base article Q112860 discusses a method for estimating the size of this table.

If you exceed the limits of this table, your application will not run. There are two primary methods you can use to stay below this boundary.

  • Remove all unused code, variables, and constants. The professional programmer should always be on the lookout for dead code in need of pruning. Extra code and variables add to the complexity of the source code without providing any benefit to the user. Remove such dead weight from your application.

  • Use the same names over and over for the same objects. This is especially true for variables. When you have a local variable that serves the same purpose in several procedures, give it the same name. This not only keeps the size of the Project Name Table small, it also gives the reader of the code a quicker understanding of new routines encountered during a walk through the code. Make a list of some handy names that you will use frequently. Included in my own list are the common variables listed in Table 9.10. This reuse rule also applies to line labels, module-level variables and constants, and any other object name in your application that appears repeatedly in different procedures or modules.

    Table 9.10. Common Variable Names
    VariableTypeDescription
    bFoundBooleanBoolean value indicating whether a condition was met during a series of tests.
    lActiveIDLongPrimary key value for the main database table in use by a procedure.
    nCounterIntegerGeneric loop counter.
    nPosIntegerReturn value from InStr( ) function call.
    sSQLStringString to hold SQL statements for database access.
    rsInfoRecordsetGeneric Recordset variable used with ActiveX Data Objects (ADO) and Data Access Objects (DAO) programming.
    sWorkStringGeneric temporary string.

Data Typing of Literals

Literals include all numeric, string, and date values that are entered directly into your source code. For example, in the statement

nDays = 365

the value 365 is a literal number. Literal strings are surrounded by double-quote marks, while literal dates begin and end with number signs.

sMessage = "An error occurred."
dtDeclaration = #7/4/1776#

When you enter a date literal from the 1900s into the Visual Basic development environment, some versions of Visual Basic will strip off the first two digits of a four-digit year. To defeat this feature, enter such date literals as strings, with or without the CDate function.

dtAction = "9/23/1999"
    ' ----- or
dtAction = CDate("9/23/1999")

By default, all literals are of type Variant. Table 9.11 lists the various type declaration characters defined by Visual Basic that can be used with literals to coerce them into a different data type.

Table 9.11. Data Types and Declaration Characters
Data TypeDeclaration CharacterDescription
Boolean There is no declaration character available for the Boolean data type, but then again, there are only two literals, True and False. True and False literals can be assigned to variables from a variety of data types. Be aware that the Boolean data type will sometimes be converted to an integer value (-1 or 0), and sometimes to a string value ("True" or "False") when it is coerced into another data type.
Byte Byte literals cannot be entered directly in Visual Basic. Use the CByte function instead.
Currency@If you are working with currency values, always use the Currency data type instead of Single or Double. Currency is not prone to the rounding errors that can occur with Single and Double values.
Decimal The Decimal data type is not a true data type at this time, but is a subtype of the Variant data type.
Double#Double is the default format for floating point literals. Do not use Double values for currency, as they are prone to rounding errors. Use the Currency data type instead.
Integer%Integers are also known as "short integers" because of their small range when compared to values in the Long data type.
Long&Longs are also known as "long integers" because of their extended range when compared to values in the Integer data type.
Object You cannot create an object literal, except to make an object undefined through the Nothing keyword.
Single!Do not use Single values for currency, as they are prone to rounding errors. Use the Currency data type instead.
String$It is not possible to use the "$" type declaration identifier with a string literal. Any literal appearing between double-quote marks is a string by definition.
Variant Every literal that is not coerced with a type declaration character is automatically a Variant.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.112.203