Errors, Constants, and Variables

This chapter will cover numerous VBScript topics. It opens with a discussion of VBScript statements and their syntax requirements and then describes how to correct and fix these types of errors. Statements that create VBScript comments and define constants and variables are also reviewed. In addition, the chapter will provide information regarding the use of built-in VBScript constants. Various topics related to variables, including variable naming rules and ways to limit variables' scope, will also be discussed.

VBScript Statements

VBScript is made up of a number of programming statements, each of which performs a specific function. Table 2.1 provides a list of the statements that make up the VBScript programming language. This chapter will cover the VBScript statements that deal with VBScript comments, constants, and variables.

Table 2.1: VBScript Statements

Statement

Description

Call

Redirects flow control in the script to a procedure

Class

Defines a class name

Const

Defines a constant

Dim

Defines a VBScript variable

Do…Loop

Repeats a group of statements as long as a condition is True or until the condition becomes True

Erase

Reinitializes the elements in an array

Execute

Runs the specified statement

ExecuteGlobal

Runs the specified statement in a script's global namespace

Exit

Terminates a loop, sub, or function

For Each…Next

Iteratively processes the contents of an array or collection

For…Next

Repeats a loop a specified number of times

Function

Defines a function name and its arguments

If…Then…Else

Performs the execution of one or more statements based on the value of the tested expression

On Error

Turns on error handling

Option Explicit

Explicitly declares all variables in your script

Private

Defines a private variable

Property Get

Defines a property name and its arguments and returns its value

Property Let

Defines a property procedure's name and arguments

Property Set

Defines a property procedure's name and arguments

Public

Defines a public variable

Randomize

Initializes the random-number generator

ReDim

Defines or redefines dynamic-array variables

Rem

Used to place comments in scripts

Select Case

Defines a collection of tests and executes only one based on the value of an expression

Set

Assigns object references to variables

Sub

Defines a Sub name and its arguments

While…Wend

Performs the execution of one or more statements as long the specified condition remains True

With

Associates a series of statements that are to be executed for a specified object


VBScript Statement Syntax

Every VBScript statement has a unique syntax that must be carefully followed in order to perform a specific task when VBScripts execute. The chapters in this book will outline the specific syntax requirements of individual VBScript statements the first time that the statements are formally introduced and will provide examples of their use.

In addition to the syntax requirements specific to individual VBScript statements, there are a number of general rules that you must follow when writing your VBScript. These rules are outlined below.

  • By default, all VBScript statements must be placed on one line.
  • You may place two or more statements on a single line by ending each statement with the colon (:) character.
  • You may spread a single statement over multiple lines by adding the underscore (_) character, known as the continuation character, to the end of each line.
  • By default, VBScript is not case sensitive, meaning that different uses of case in the spelling of constants, variables, subroutine names, and function names are permitted.
  • Strict enforcement of case sensitivity can be mandated by adding the Option Explicit statement to the beginning of a VBScript.

Syntax Errors

There are several types of errors that can occur during the execution of a VBScript. These errors include logical errors, in which the script produces unexpected results because of faulty logic on the part of the programmer, and run-time errors, which occur when a script attempts to do something that it cannot do. For example, run-time errors occur when scripts attempt to access objects that do not exist or are not available, which can be the case for both local and network disk drives. The third category of error is the syntax error, which occurs when programmers fail to use the proper syntax in the formulating of a VBScript statement. Unlike run-time errors, which occur during the execution of the script, syntax errors are flagged by the scripting engine during interpretation, thus preventing the script from even starting.

Run-time errors can be difficult to track down and find because they may be hidden in a seldom used portion of code within the script. On the other hand, a syntax error anywhere in a script will prevent its execution. Therefore, syntax errors should be easily discovered and fixed during initial script development and testing. For example, the following statement will produce the error shown in Figure 2.1 when run by the WSH.

click to expand
Figure 2.1: Failure to follow a VBScript statement's syntax results in an error that terminates the script's execution

MsgBox "Text must be enclosed within a pair of double quotation marks"

MsgBox() is a built-in VBScript function that can be used to display text in a pop-up dialog box. It requires that the text to be displayed must be enclosed within a matching pair of double quotation marks. In the previous example, the second double quotation mark is missing.

Table 2.2 provides a list of VBScript errors that can occur as a result of not following the syntax rules for VBScript statements. An error number is assigned to every VBScript syntax error. Depending on the host environment in which VBScripts run, these error messages may be reported in either a hexadecimal or decimal format. Table 2.2 provides both the hexadecimal and decimal error numbers associated with each syntax error message.

Table 2.2: VBScript Syntax Errors

Hexadecimal

Decimal

Description

800A03E9

1001

Out of Memory

800A03EA

1002

Syntax error

800A03ED

1005

Expected ‘ (‘

800A03EE

1006

Expected ‘) ‘

800A03F2

1010

Expected identifier

800A03F3

1011

Expected ‘='

800A03F4

1012

Expected ‘If '

800A03F5

1013

Expected ‘To'

800A03F5

1013

Invalid number

800A03F6

1014

Expected ‘End'

800A03F6

1014

Invalid character

800A03F7

1015

Expected ‘Function'

800A03F7

1015

Unterminated string constant

800A03F8

1016

Expected ‘Sub'

800A03F9

1017

Expected ‘Then'

800A03FA

1018

Expected ‘Wend'

800A03FB

1019

Expected ‘Loop'

800A03FC

1020

Expected ‘Next'

800A03FD

1021

Expected ‘Case'

800A03FE

1022

Expected ‘Select'

800A03FF

1023

Expected expression

800A0400

1024

Expected statement

800A0401

1025

Expected end of statement

800A0402

1026

Expected integer constant

800A0403

1027

Expected ‘While' or ‘Until'

800A0404

1028

Expected ‘While', ‘Until', or end of statement

800A0405

1029

Expected ‘With'

800A0406

1030

Identifier too long

800A040D

1037

Invalid use of ‘Me' keyword

800A040E

1038

‘loop' without ‘do'

800A040F

1039

Invalid ‘exit' statement

800A0410

1040

Invalid ‘for' loop control variable

800A0411

1041

Name redefined

800A0412

1042

Must be first statement on the line

800A0414

1044

Cannot use parentheses when calling a Sub

800A0415

1045

Expected literal constant

800A0416

1046

Expected ‘In'

800A0417

1047

Expected ‘Class'

800A0418

1048

Must be defined inside a class

800A0419

1049

Expected Let or Set or Get in property declaration

800A041A

1050

Expected ‘Property'

800A041B

1051

Number of arguments must be consistent across properties' specification

800A041C

1052

Cannot have multiple default properties/methods in a class

800A041D

1053

Class initialize or terminate do not have arguments

800A041E

1054

Property Set or Let must have at least one argument

800A041F

1055

Unexpected Next

800A0421

1057

‘Default' specification must also specify ‘Public'

800A0422

1058

‘Default' specification can only be on Property Get

Syntax errors are generally relatively easy to correct. The error messages that appear when syntax errors are discovered identify the error as well as the line number where the error occurred. Usually a quick review of the syntax for the offending statement is all that is required to identify and correct the error.

  Note

Detailed coverage of run-time errors and how to handle and recover from them is provided in Chapter 6, "Data Collection, Notification, and Error Reporting."

Displaying Syntax Errors within Internet Explorer

The WSH always displays errors when they occur. However, by default, Internet Explorer suppresses the display of error messages. This works well since most users will not understand the error messages or be able to do anything about them anyway. Instead, Internet Explorer displays a small yellow icon in the bottom left-hand corner of the browser's status bar whenever an error occurs.

For example, the following HTML page contains the same type of VBScript error as the previous WSH example did. If you save and run it, you will see that Internet Explorer flags the error as demonstrated in Figure 2.2.

click to expand
Figure 2.2: Internet Explorer automatically suppresses the display of VBScript error messages


 

Script 2.2 - VBScript syntax error example

To view the error message that caused Internet Explorer to display the yellow icon, double-click on the icon and the error will be displayed as demonstrated in Figure 2.3.

click to expand
Figure 2.3: Examining a typical script error within Internet Explorer

  Tip

Internet Explorer's suppression of VBScript errors is generally inconvenient for most VBScript programmers because it forces them to search for and display errors. Fortunately, Internet Explorer is flexible enough to allow you to configure it to automatically display script error messages using the following procedure:

  1. Open Internet Explorer and select Internet Options from the Tools menu. The Internet Options dialog box appears.
  2. Select the Advanced property sheet.
  3. Select the Display a notification about every script error option and click OK.


Documenting VBScripts with Comments

Comments provide the ability to make scripts self-documenting, making them easier for others to support. You can add comments to VBScripts using the Rem statement. The syntax for the Rem statement is shown below.

Rem comments

For example, the Rem statement can be used as demonstrated below.

Rem The VBScript MsgBox() function displays text messages
MsgBox "Greetings!"

Alternatively, you can substitute the single quotation mark () character for the Rem keyword as shown below.

' The VBScript MsgBox() function displays text messages
MsgBox "Greetings!"

Comments can also be added to the end of a VBScript statement. In order to use the Rem statement to add the comment to the end of a VBScript statement, you must first precede it with a colon, as demonstrated below.

MsgBox "Greetings!" : Rem The VBScript MsgBox() function displays text messages

However, if you use the character in place of the Rem keyword, you can omit the colon, as shown below.

MsgBox "Greetings!" ' The VBScript MsgBox() function displays text messages

Another good use of comments is in the creation of a script template, as demonstrated below.

'*************************************************************************
'Script Name: ScriptName.vbs
'Author: Author Name
'Created: mm/dd/yyyy
'Description: Place a brief description of the script here
'*************************************************************************

'Initialization Section

'Main Processing Section

'Procedure Section

You will see this template used to document all the WSH scripts that appear in the project sections of this book. The first part of the template provides a place for recording information about the script. The Initialization Section will contain VBScript statements that globally affect the entire script or that define constants, variables, arrays, and objects. The Main Processing Section will contain the VBScript statements that control the overall execution of the script, and the Procedure Section will be used to store all of the procedures that make up the script.

  Note

Because of the nature and design of HTML pages, it is difficult to design a VBScript template appropriate for that programming environment. However, the liberal use of comments should still be applied to VBScripts embedded inside HTML pages in order to make them easier to understand and support.

Only Internet Explorer and Internet Explorer compatible browsers are able to run VBScripts. Problems will therefore occur when visitors with non-Internet Explorer compatible browsers attempt to access Web pages that contain embedded VBScripts, resulting in the display of the text of the VBScripts statements as if they were part of the Web page's content. The VBScript statements are displayed as text because browsers that do not recognize or support VBScript to not know what else to do with the VBScript statements.

This undesirable behavior can be avoided by simply hiding VBScript statements from non-Internet Explorer compatible browsers. This trick is achieved using the HTML and –> comment tags along with the VBScript comment statement, as demonstrated below.



Note that the HTML comment tags have been inserted immediately after the first tag. All browsers, even those that do not support VBScript, know not to display text contained in the tags. Browsers that support VBScript will process the VBScript and ignore the first HTML comment. They will also ignore the VBScript comment, thus hiding the last HTML comment. On the other hand, browsers that do not support VBScript will ignore all the VBScript statements between the opening and closing HTML comment tags.


Storing and Retrieving Data from Memory

Like any programming language, VBScript needs to be able to store and retrieve data from memory as it executes. In support of this requirement, VBScript provides three statements that can be used to define constants, variables, and arrays. These statements are outlined in Table 2.3.

Table 2.3: VBScript Statements That Define Data Storage

Statement

Description

Const

Defines a VBScript constant

Dim

Defines a VBScript variable or array

ReDim

Defines a dynamic VBScript array

Using Constants

A constant is a value that does not change during the execution of a script. If a script has a known value that will never need to be changed during its execution, it can be stored as a constant. An example of a constant is the value of pi. Constants can be used in two different ways within VBScripts. First, you can define your own custom constants. Second, you can reference built-in VBScript run-time constants.

You cannot change the value assigned to a constant once it has been defined. This protects constants and prevents their accidental modification. Any attempt to change the value of a constant results in an "Illegal assignment xxxxxxxx" error, where xxxxxxxx is the name of the constant that the script attempted to modify.

Defining Constants

Constants are defined using the Const statement, which has the following syntax:


[Public | Private] Const cCONSTANT = expression

Public and Private are optional keywords. Public makes the constant available throughout the entire script. Private limits the ability to access a constant to the procedures where it is defined. cCONSTANT is the name assigned to the constant, and expression is the value to be assigned.

  Tip

Consider applying a naming convention to all your constants to make them stand out from the rest of your code. In this book, constants are created using the following naming conventions:

  • Constant names describe their contents.
  • The first letter of the constant name begins with the lowercase letter c.
  • The rest of the name is spelled out in all uppercase.
  • The underscore character is used to separate the words that make up the constant's name in order to improve readability.

The following example demonstrates how to define a constant and assign it a numeric value.


Const cTOTAL_VALUE = 1000

To define a string, you must place the value assigned to the constant within quotes, as demonstrated below.


Const cCOMPANY_NAME = "XYZ Inc."

Similarly, to define a date, place the value inside a pair of matching pound signs, as shown below.


Const cPROJECT_DEADLINE = #03-30-03#

Constants can be used for a variety of purposes. For example, one use of constants is to establish a common title bar message in pop-up dialog boxes displayed by your scripts, as demonstrated below.


Const cTITLEBAR_MSG = "Data Collection Utility"
MsgBox "Click on OK to continue.", , cTITLEBAR_MSG
MsgBox "Click on OK to post saved data.", , cTITLEBAR_MSG

When executed, the previous example displays the pop-up dialog boxes shown in Figures 2.4 and 2.5.

click to expand
Figure 2.4: Creating a standard title bar message using a constant

click to expand
Figure 2.5: Using a constant instead of hard coding data to make scripts easier to maintain

Referencing VBScript Run-Time Constants

VBScript supplies programmers with a large collection of predefined constants. By adding references to these constants within your scripts, you can save time and simplify your code. For example, the following statement uses the vbOkCancel MsgBox() constant to display a pop-up dialog box that displays the OK and Cancel buttons.


MsgBox "Do you wish to continue?", vbOkCancel

The MsgBox() function is a built-in VBScript function that is used to display messages in pop-up dialog boxes. vbOkCancel is just one of a number of constants that you can use to specify the appearance of your pop-up dialog boxes. For more information on the constants associated with the MsgBox() function, refer to Chapter 6.

VBScript also provides an extensive collection of constants that reference dates and times. Table 2.4 displays a list of these constants.

Table 2.4: VBScript Date and Time Constants

Constant

Value

Description

vbSunday

1

Sunday

vbMonday

2

Monday

vbTuesday

3

Tuesday

vbWednesday

4

Wednesday

vbThursday

5

Thursday

vbFriday

6

Friday

vbSaturday

7

Saturday

vbFirstFourDays

2

First full week with a minimum of four days in the new year

vbFirstFullWeek

3

First full week of the year

vbFirstJan1

1

Week that includes January 1

vbUseSystemDayOfWeek

0

Day of week as specified by the operating system

The date and time constants shown in Table 2.4 can be used as demonstrated below.


TodaysDate = Weekday(Date())
If TodaysDate = vbMonday then MsgBox "Please reset time clocks."

In this example, a pop-up dialog box is displayed only if the script is executed on a Monday. Another example of built-in constants is VBScript's collection of string constants, shown in Table 2.5.

Table 2.5: VBScript String Constants

Constant

Value

Description

vbCr

Chr(13)

Executes a carriage return

vbCrLf

Chr(13)

and Chr(10) Executes a carriage return and a line feed

vbFormFeed

Chr(12)

Executes a form feed

vbLf

Chr(10)

Executes a line feed

vbNewLine

Chr(13)

and Chr(10) Adds a newline character

vbNullChar

Chr(0)

Creates a 0 or null character

vbNullString

String with no value

Creates an empty string

vbTab

Chr(9)

Executes a horizontal tab

vbVerticalTab

Chr(11)

Executes a vertical tab

You can use string constants to format script output, as demonstrated in the following example.


Const cTITLEBAR_MSG = "VBScript String Constant Example"
MsgBox "This example demonstrates how to use VBScript" & vbCrLf & _
 "string constants to format text output." & vbCrLf & vbCrLf & _
 vbTab & "End of Example", , cTITLEBAR_MSG

As you can see from the previous example, the vbCrLf constant can be used to execute a carriage return and a line feed while the vbTab constant executes a tab operation.

  Tip

Note the use of the ampersand (&) character and the underscore (_) character in the previous example. The & character is a VBScript string concatenation operator. Its purpose is to create a single string by joining two smaller strings. The _ character is used to continue a VBScript statement across another line.

Figure 2.6 shows the pop-up dialog box that is displayed by the previous code.

click to expand
Figure 2.6: Using VBScript string constants to exercise control over the output displayed in pop-up dialog boxes

Creating Variables

While constants are certainly the right mechanism for storing data that will not change during a script's execution, in most cases, you will find that you need to manipulate the data used by your scripts. In this case, the data should be defined as a variable.

VBScript supports a single type of variable known as a variant. However, variants are flexible and can be used to store many different types of data, as listed in Table 2.6.

Table 2.6: VBScript Supported Variant Subtypes

Subtype

Description

Boolean

A variant with a value of True or False

Byte

An integer whose value is between 0 and 255

Currency

A currency value between -922,337,203,685,477.5808 and 922,337,203,685,477.5807

Date

A number representing a date between January 1, 100 and December 31, 9999

Double

A floating-point number with a range of -1.79769313486232E308 and - 4.94065645841247E-324 or 4.94065645841247E-324 and 1.79769313486232E308

Empty

A variant that has not been initialized

Error

A VBScript error number

Integer

An integer with a value that is between -32,768 and 32,767

Long

An integer whose value is between -2,147,483,648 and 2,147,483,647

Null

A variant set equal to a null value

Object

An object

Single

A floating-point number whose value is between -3.402823E38 and - 1.401298E-45 or 1.401298E-45 and 3.402823E38

String

A string up to 2 billion characters long

Variants recognize the type of data assigned to them and behave accordingly. However, you can exercise some control over how VBScript views the data that you assign to variables. For example, you can define a numeric value to a variable as follows:


intTotalCount = 100

To assign a string to a variable, enclose it inside a matching pair of quotation marks, as demonstrated in both of the following examples.


strName = "William Ford"
Age = "4"

To explicitly assign data to a variable, place the data inside a pair of matching pound signs, as demonstrated below.


dtmDateOfBirth = #03/24/99#

You can use built-in VBScript functions to convert data from one type to another, as demonstrated below.


varDateOfBirth = #03/24/99#
varDateOfBirth = CStr(varDateOfBirth)

In this example, the type of value stored by varDateOfBirth is converted from a date to a string.

  Note

VBScript supplies a number of conversion functions, including Asc() , Cbool(), Cbyte(), Cbur(), Cdate(), CDbl(), Chr(), Cint(), CLng(), CSng() and CStr(). To find more information about these functions refer to Chapter 4, "Procedures."

Variable Naming Rules

VBScript has a number of rules that must be followed when assigning names to variables. These rules include:

  • Variables must be unique within their scope.
  • Variable names must be less than 256 characters long.
  • Variable names must begin with an alphabetic character.
  • Variable names cannot contain spaces.
  • Variable names can only consist of alphabetic and numeric characters and the _ character.
  • Variable names cannot consist of VBScript reserved words.

Variable names are not case sensitive, meaning the capitalization does not affect the way that VBScript sees a variable's name. Therefore, VBScript sees all three of the following variable names as the same:


strUnitColor
strUNITCOLOR
strunitcolor

Mixing capitalization styles makes for confusing code and is highly discouraged. Stick with a consistent case throughout your VBScripts and develop a variable naming scheme. For example, many programmers use descriptive words or abbreviations as components of variable names. In addition, capitalizing the first letter of each word or abbreviation helps to make variable names more readable. Another good technique to use when naming variables is to append a three-character prefix identifying the type of data stored in a variable. This is known as Hungarian Notation. Table 2.7 lists prefixes commonly used to name variables.

Table 2.7: Hungarian Prefixes

Prefix

Variable Subtype

Boolean

bln

Byte

byt

Currency

cur

Date

dtm

Double

dbl

Error

err

Integer

int

Long

lng

Object

obj

Single

sng

String

str

Variant

var

The following examples demonstrate the use of variables that follow the conventions stated above.


strUserName = "Molly Ford"
intUnitCount = 100

Defining Variables

VBScript allows variables to be defined dynamically or formally. To dynamically define a variable, you simply begin using it, as demonstrated below.


intTotalCount = intTotalCount + 1

Dynamically creating variables is considered to be bad form. Formal variable declaration is strongly preferred. Formal variable declaration makes scripts easier to read and support. VBScript provides the Dim statement as a means of formally defining a variable. The syntax of this statement is shown below.


Dim variablename

Variablename is the name of the variable being defined. For example, the following example defines a new variable called intTotalCount and then begins working with the variable.


Dim intTotalCount
intTotalCount = intTotalCount + 1

To reduce the number of lines of code required to define variables, VBScript permits you to define more than one variable at a time using a single Dim statement, as demonstrated below.


Dim intTotalCount, intAvgCount, intFinalCount

Even if you formally define all your variables, there is always the possibility that you may mistype the name of a variable somewhere in your script. When this happens, VBScript simply sees the mistyped variable as a new variable. VBScript allocates memory to it, assigns it a value of empty, and continues running.

For example, take a look at the following script.


Dim intUnitCount
intUnitCount = 5
intUnitCount = intUnitCoun + 1
MsgBox intUnitCount

In this example, a variable called intUnitCount is defined. It is then assigned a value of 5. The third statement was supposed to add 1 to this value, but a typo was made, creating a new variable called intUnitCoun. As a result, when the value of intUnitCount is displayed, it shows a value of 1 instead of 6. This is because VBScript assigned a value of 0 to intUnitCoun. To prevent this from happening, you can add the Option Explicit statement to the beginning of your VBScripts. This statement forces the explicit declaration of all variables within the script. For example, if you modify the previous example as shown below and run it, you'll see the error shown in Figure 2.7 appear.

click to expand
Figure 2.7: The Option Explicit statement flags all undefined variables, allowing you to fix them during script development


Option Explicit
Dim intUnitCount
intUnitCount = 5
intUnitCount = intUnitCoun + 1
MsgBox intUnitCount
  Note

VBScript imposes a limit of 127 script-level variables per script and 127 procedure-level variables per procedure.

Variable Scope and Lifetime

Variable scope refers to the locations within a script where a variable can be referenced. Lifetime refers to the period of time that a variable exists. Any variables defined at the beginning of a script have a global scope, meaning that they can be accessed by any location within the script. In addition, they exist for as long as the script executes.

A variable with a local scope is one that is defined within a procedure. A procedure is a collection of statements that are called and processed as a unit. VBScript supports two types of procedures, subroutines and functions. Procedures are covered in detail in Chapter 4. Variables defined within procedures cannot be accessed from outside of the procedure. In addition, the variable's lifetime is limited to the period of time that the procedure executes.


Other Sources of Data

So far, all the examples that you have seen in this chapter have assumed that any data that the script will need to work with will be hard coded within the script. In reality, scripts are seldom written this way. Instead, data is collected for processing from numerous sources. These sources include:

  • The InputBox() function. This function provides the ability to display a pop-up dialog box that displays an input text field, which the user can use to provide input data to the script. This function is covered in Chapter 6.
  • Data read from input files. Chapter 17, "Using Configuration Files to Control Script Execution," demonstrates how to collect script input from files.
  • Data read from the Windows registry. Chapter 22, "Developing the Setup Script," demonstrates the techniques involved in using the registry as a data source.
  • Data passed to the script as arguments. Chapter 7, "VBScript Objects," describes the process involved in setting up a script to accept arguments passed to it at run time.


Using Operators to Manipulate Variables

To assign a value to a variable or to change the value assigned to a variable, you simply need to assign it a value using the equal sign (=) as follows.


intUnitCount = 10

Using the equal sign in conjunction with the VBScript arithmetic operators listed in Table 2.8, you can modify the values assigned to variables in a variety of ways. For example, the following script defines a variable named intUnitCount, assigns it an initial value of 10, and then proceeds to change its assigned value several times.

Table 2.8: VBScript Arithmetic Operators

Operator

Description

+

Add

-

Subtract

*

Multiply

/

Divide

Integer division

Mod

Modulus

-x

Reverses the sign of x

Exponentiation


Dim intUnitCount
intUnitCount = 9 'intUnitCount = 9
intUnitCount = intUnitCount + 1 'intUnitCount = 10
intUnitCount = intUnitCount * 10 'intUnitCount = 100
intUnitCount = intUnitCount / 2 'intUnitCount = 50
intUnitCount = intUnitCount / 2 + 1 * 5 'intUnitCount = 30
MsgBox "intUnitCount = " & intUnitCount

When executed, this script displays the results shown in Figure 2.8.


Figure 2.8: Using VBScript operators to manipulate the value assigned to a variable

When an expression consists of more than one calculation, VBScript resolves the value of the expression by performing calculations based on a strict order of precedence. Exponentiation is performed first. Then negation occurs, followed by multiplication and division and so on. Table 2.9 outlines VBScript's order of precedence.

Table 2.9: VBScript Order of Precedence

Operators

Description

-

Negation

Exponentiation

*, /

Multiplication and division

Integer division

Mod

Modulus

+, -

Addition and subtraction

Note: Operators listed at the beginning of the table are evaluated before those that appear later in the table.

You can alter the order in which VBScript performs calculations when resolving an expression by enclosing parts of the expression inside parentheses. For example, examine the following expression:


intUnitCount = 10
intUnitCount = intUnitCount / 2 + 1 * 5

When resolving this expression, VBScript begins by dividing 10 by 2, getting a result of 5. Next it multiplies 1 by 5, getting a result of 5. Finally, it adds 5 plus 5, getting a final result of 10. Now look at how adding parentheses to the expression changes the results produced when VBScript resolves the value of the expression.


intUnitCount = 10
intUnitCount = ((intUnitCount / 2) + 1) * 5

In the case of this example, VBScript first divides 10 by 2, getting 5. It then adds 1 to 5, getting 6. Finally it multiplies 5 by 6 for a final result of 30.


VBScript Reserved Words

Like all programming languages, VBScript sets aside a collection of words, called reserved words, for its own use. You are not permitted to use these words as variable, procedure, constant, or other type or identifier names. When used, these words must be applied exactly as intended by VBScript, as outlined in its documentation. A list of VBScript's reserved words is displayed in Table 2.10.

Table 2.10: VBScript Reserved Words

And

EndIf

LSet

RSet

As

Enum

Me

Select

Boolean

Eqv

Mod

Set

ByRef

Event

New

Shared

Byte

Exit

Next

Single

ByVal

False

Not

Static

Call

For

Nothing

Stop

Case

Function

Null

Sub

Class

Get

On

Then

Const

GoTo

Option

To

Currency

If

Optional

True

Debug

Imp

Or

Type

Dim

Implements

ParamArray

TypeOf

Do

In

Preserve

Until

Double

Integer

Private

Variant

Each

Is

Public

Wend

Else

Let

RaiseEvent

While

ElseIf

Like

ReDim

With

Empty

Long

Rem

Xor

End

Loop

Resume

 


Summary

This chapter reviewed VBScript syntax errors and provided examples of how to identify and correct them. The chapter provided a complete list of VBScript language statements and provided coverage of the statements that define comments, constants, and variables. Also discussed was how to store data in and reference constants and variables. This discussion included a look at built-in VBScript constants and ways to limit the scope of VBScript variables.


Chapter 3 Conditional Logic and Iterative Structures

Part I - Introducing Microsoft VBScriptBasics

Part II - Professional Project 1 Desktop Administration Using VBScript and the WSH

Part III - Professional Project 2 Analyzing Application Logs

Part IV - Professional Project 3 Creating a Centralized Report Management Station

Part V - Professional Project 4 Reporting Application Summary Data via the Web

Part VI - Introducing Microsoft VBScriptBasics



Microsoft VBScript Professional Projects
Microsoft VBScript Professional Projects
ISBN: 1592000568
EAN: 2147483647
Year: 2005
Pages: 366

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net