VBS
VBSCRIPTCRIPT – – TTHEHEBBASICSASICS... ... ... ... ... ... ... 22 W
WHAT IS A VARIABLEHAT IS A VARIABLE?...?... 33 V
VARIABLESARIABLES N NAMINGAMINGR R ESTRICTIONSESTRICTIONS... 33 H
HOWOWDDOOII CCREATE AREATE AVVARIABLEARIABLE??... 33 D
DECLARATIONECLARATIONSSTATEMENTS ANDTATEMENTS ANDHHIGHILIGTSIGHILIGTS... 33 Dim
Dim StatementStatement ... 33 Overriding
Overriding Standard Standard Variable Variable Naming Naming Conventions...Conventions... 44 Declaring
Declaring Variables Variables Explicit aExplicit and nd ImplicitImplicit ... 44 Option
Option Explicit Explicit Statement.Statement... 55 W
WORKING WITHORKING WITHAARRAYSRRAYS... ... ... ... ... ... 55 S
SCALAR CALAR VVARIABLES ANDARIABLES ANDAARRAYRRAYVVARIABLESARIABLES... 66 C
CREATINGREATINGAARRAYSRRAYS... 66 Fixed
Fixed Length Length ArraysArrays ... 66 Dynamic
Dynamic Arrays...Arrays... 66 Resizing
Resizing a a dynamic dynamic array array without without Preserve...Preserve... 77 Resizing
Resizing a a dynamic dynamic array array with with Preserve...Preserve... 77 Array
Array Iterations...Iterations... 88 VBS
VBSCRIPTCRIPTCCONSTANTSONSTANTS... ... ... ... ... ... ... 88 W
WORKING WITH CONSTANTSORKING WITH CONSTANTS... 88 D
DECLARING CONSTANTSECLARING CONSTANTS... 99 VBS
VBSCRIPT PRECRIPT PRE--DEFINED CONSTANTSDEFINED CONSTANTS... 1010 T
THEHESSCOPE ANDCOPE ANDLLIFETIME OF AIFETIME OF AVVARIABLEARIABLE... ... ... ... ... 1111 P
PRIVATERIVATESSTATEMENTTATEMENT... 1111 P
PUBLICUBLICSSTATEMENTTATEMENT... 1212 VBS
VBSCRIPTCRIPTOOPERATORSPERATORS... ... ... ... ... ... .. 1414 W
WORKING WITHORKING WITHOOPERATORSPERATORS... 1414 A
ARITHMETICRITHMETICOOPERATORSPERATORS... 1515 Addition Addition (+)(+) ...1515 Subtraction Subtraction (-)(-)... 1515 Multiplication Multiplication (*)...(*)... 1515 Division (/)
Division (/) and and Integer Integer Division (\)Division (\) ...1616 Exponent
Exponentiation iation (^) (^) ... 1616 Modulus
Modulus Arithmetic Arithmetic (Mod)...(Mod)... 1616 Unary
Unary Negation Negation (-)...(-)... 1616 String
String Concatenation Concatenation (&)(+)...(&)(+)... 1616 C
COMPARISONOMPARISONOOPERATORSPERATORS... 1616 Equality
Equality (=)...(=)... 1717 Inequality
Inequality (<>)(<>)... 1717 Less T
Less Than (<) han (<) and Greater and Greater Than (Than (>)>) ...1717 Less than or
Less than or equal (<=), greater equal (<=), greater than or equal than or equal to (>=)to (>=) ...1717 Object
Object Equivalence Equivalence (Is) (Is) ...1717 L
LOGICALOGICALOOPERATORSPERATORS... 1717 Logical
Logical Negation Negation (Not)...(Not)... 1818 Logical
Logical Conjunction Conjunction (And)...(And)... 1818 Logical
Logical Disjunction Disjunction (Or)...(Or)... 1919 Logical
Logical Exclusion Exclusion (Xor)(Xor) ...1919 Logical
Logical Equivalence Equivalence (Eqv)(Eqv) ... 2020 Logical
Logical Implication Implication (Imp)...(Imp)... 2020 F
FLOWLOWCCONTROLONTROL... ... ... ... ... ... ... 2121 C
W
WHYHYCCONTROL THEONTROL THEFFLOW OFLOW OFCCODEODE? ? ... 2121 U
USINGSINGCCONTROLONTROLSSTRUCTURES TOTRUCTURES TOMMAKEAKEDDECISIONSECISIONS... 2222 Making
Making Decisions Decisions Using Using If...Then...If...Then...ElseElse... 2222 D
DECIDINGECIDINGBBETWEENETWEENSSEVERALEVERALAALTERNATIVESLTERNATIVES... 2424 Select
Select CaseCase... 2626 U
USINGSINGCCONTROLONTROLSSTRUCTURES TOTRUCTURES TOMMAKEAKECCODEODER R EPEATEPEAT... 2828 Using
Using For...Next For...Next Statement Statement ... 2828 Using
Using For For Each...Next Each...Next Statement...Statement... 3131 Using
Using Do…Loops Do…Loops Statement...Statement... 3232 Using
Using While. While. . . .Wend .Wend Statement...Statement... 3434 P
PUTTING ALL TOGETHER UTTING ALL TOGETHER ... 3535 S
SUBROUTINES ANDUBROUTINES ANDFFUNCTIONUNCTIONPPROCEDURESROCEDURES... ... ... ... ... 3636 W
WHATHATAAREREFFUNCTIONSUNCTIONS? ? ... 3636 S
SUBUBPPROCEDURESROCEDURES... 3636 F
FUNCTIONUNCTIONPPROCEDURESROCEDURES... 3737 D
DECLARINGECLARINGSSUBROUTINESUBROUTINES/F/FUNCTIONSUNCTIONS... 3737 C
CALLING AALLING ASSUBROUTINEUBROUTINE... 3838 C
CALLALLSSTATEMENTTATEMENT... 3939 C
CALLING AALLING AFFUNCTIONUNCTION... 4040 E
EXITING AXITING ASSUBROUTINEUBROUTINE/F/FUNCTIONUNCTION... 4141 P
PASSINGASSINGAARGUMENTS INTORGUMENTS INTOPPROCEDURESROCEDURES... 4141 W
WHYHYAAREREPPROCEDURESROCEDURESUUSEFULSEFUL?? ... 4242 Exit
Exit StatementStatement... 4444 C
CODINGODINGCCONVENTIONSONVENTIONS... ... ... ... ... ... .. 4545 C
CONSTANTONSTANT N NAMINGAMINGCCONVENTIONSONVENTIONS... 4545 V
VARIABLEARIABLE N NAMINGAMINGCCONVENTIONSONVENTIONS... 4646 D
DESCRIPTIVEESCRIPTIVEVVARIABLE ANDARIABLE ANDPPROCEDUREROCEDURE N NAMESAMES... 4646 O
OBJECTBJECT N NAMINGAMINGCCONVENTIONSONVENTIONS... 4646 C
CODEODECCOMMENTINGOMMENTINGCCONVENTIONSONVENTIONS... 4747 F
FUNCTIONS ANDUNCTIONS ANDSSUBUBSSTANDARDSTANDARDS... 4747 Procedure
Procedure Header...Header... 4747 T
THEHEQQUICK UICK TTESTESTEEDITOR DITOR OOPTIONSPTIONS... 4949 Fonts
Fonts and and ColorsColors... 4949 Genera
General...l... 5050 C
CODEODEII NDENTATION NDENTATION... 5050 Q
QUICK UICK TTESTESTR R EUSABLEEUSABLEAACTIONCTIONHHEADER EADER ... 5151 C
CREATING ANREATING ANAACTIONCTIONTTEMPLATEEMPLATE... 5151
VBScript – The Basics
VBScript – The Basics
When users interact with computers, they usually get
When users interact with computers, they usually get to some point where theto some point where the computer asks them for information. That i
computer asks them for information. That i nformation is stored or manipulated bynformation is stored or manipulated by the computer in some way. Suppose, for example, that you want to keep a record the computer in some way. Suppose, for example, that you want to keep a record of the number of times the user has clicked the button. In that case, you would of the number of times the user has clicked the button. In that case, you would want to store a value in memory. In any case, you need a "container" in which to want to store a value in memory. In any case, you need a "container" in which to store information. Programmers commonly call
What is a variable?
What is a variable?
A variable is
A variable is a virtual container in the a virtual container in the computer's memory or convenientcomputer's memory or convenient placeholder that refers to a
placeholder that refers to a computer memory location where you can storecomputer memory location where you can store program information that may change during
program information that may change during the time your script is running.the time your script is running. Where the variable is stored i
Where the variable is stored in computer memory is unimportant. What isn computer memory is unimportant. What is
important is that you only have to refer to a variable by name to see or change it important is that you only have to refer to a variable by name to see or change it ss value. In
value. In VBScriptVBScript, variables are always of one fundamental data , variables are always of one fundamental data type,type, Variant.Variant. A computer program can store information in a variable and then access that A computer program can store information in a variable and then access that information later by referring to the variable's name
information later by referring to the variable's name..
Variables Naming Restrictions
Variables Naming Restrictions
Variable names follow the standard rules for naming anything in
Variable names follow the standard rules for naming anything in VBScriptVBScript. A. A variable name:
variable name:
Must begin with an alphabetic character. Must begin with an alphabetic character. Cannot contain an embedded period. Cannot contain an embedded period. Must not exceed 255 characters. Must not exceed 255 characters.
Must be unique in the scope in which it is declared. Must be unique in the scope in which it is declared.
Make sure you never create variables that have the same name as keywords Make sure you never create variables that have the same name as keywords already used by
already used by VBScriptVBScript. These keywords are called reserved words and. These keywords are called reserved words and include terms such as
include terms such as DateDate,, MinuteMinute,, SecondSecond,, TimeTime, and so on., and so on.
How Do I Create a Variable?
How Do I Create a Variable?
When you create a variable, you have to give it a name. That way, when you need When you create a variable, you have to give it a name. That way, when you need to find out what's contained in the variable, you use its name to let the
to find out what's contained in the variable, you use its name to let the computercomputer know which variable you are referring to. You have two ways to create a variable. know which variable you are referring to. You have two ways to create a variable. The first way, called the explicit method, is where you use the
The first way, called the explicit method, is where you use the DimDim keyword to tellkeyword to tell VBScript
VBScript you are about to create a variable. You then follyou are about to create a variable. You then foll ow this keyword with theow this keyword with the name of the variable. If, for example, you want to create a variabl
name of the variable. If, for example, you want to create a variabl e callede called Quantity, you would enter
Quantity, you would enter
Dim
Dim nQuantitynQuantity
And the variable will then exist. And the variable will then exist.
Declaration Statements and Highiligts
Declaration Statements and Highiligts
Dim Statement
Dim Statement
DescriptionDescription The
The DimDim statement declares and allocates storage space in memory forstatement declares and allocates storage space in memory for variables. The
variables. The DimDim statement is used either at the start of a procedure or thestatement is used either at the start of a procedure or the start of a global script block. In the first case, the variable declared using start of a global script block. In the first case, the variable declared using DimDim is local to the procedure. In the second, it's available throughout the module. is local to the procedure. In the second, it's available throughout the module.
Syntax Syntax
Dim
Dim varnamevarname[([[([subscriptssubscripts])][,])][, varnamevarname[([[([subscriptssubscripts])]] . . .])]] . . . Arguments
Arguments
Parameter Description Parameter Description
varname
varname Name of the variable; follows standard variable naming conventions.Name of the variable; follows standard variable naming conventions. subcripts
subcripts An array and optionally specifies the number and extent oAn array and optionally specifies the number and extent o f arrayf array dimensions up to 60 multiple dimensions may be declared. dimensions up to 60 multiple dimensions may be declared.
Notes Notes
When variables are first initialized with the
When variables are first initialized with the DimDim statement, they have astatement, they have a value of
value of EmptyEmpty. In addition, if a variable ha. In addition, if a variable has been initialized but nots been initialized but not assigned a value, the following expressions will both evaluate to True: assigned a value, the following expressions will both evaluate to True:
If
If vVarvVar == 00 ThenThen If
If vVar = ""vVar = "" ThenThen
Overriding Standard Variable Naming Conventions
Overriding Standard Variable Naming Conventions
You can override standard variable nami
You can override standard variable naming conventions by placing your variableng conventions by placing your variable name in brackets. This all
name in brackets. This allows you to use reserved words or illows you to use reserved words or illegal characters inegal characters in variable names. For example:
variable names. For example:
Dim [Option Explicit] Dim [Option Explicit] [
[Option ExplicitOption Explicit]] = 6= 6 Msgbox
Msgbox [[OptionOptionExplicitExplicit]]
In a common usage, is
In a common usage, is not recommended to use this syntax. However, is not recommended to use this syntax. However, is possible.possible. Those overriding naming convention are useful for user custom classes.
Those overriding naming convention are useful for user custom classes. For more information about classes, in t
For more information about classes, in the advanced topic of he advanced topic of VBScript.VBScript.
Declaring Variables Explicit and Implicit
Declaring Variables Explicit and Implicit
You declare variablesYou declare variables explicitlyexplicitly in your script using thein your script using the DimDim statement, thestatement, the Public
Public statement, and thestatement, and the PrivatePrivate statement.statement.
Dim
Dim nDegreesFahrenheitnDegreesFahrenheit
You declare variables
You declare variables explicitlyexplicitly in your script using thein your script using the DimDim statement, thestatement, the Public
Public statementstatement,, and theand the PrivatePrivate statementstatement..
Dim
Dim nDegreesFahrenheitnDegreesFahrenheit
You declare multiple variables by separating each variable name with a comma. You declare multiple variables by separating each variable name with a comma.
Dim
Dim nTop, nBottom, nLeft, nRightnTop, nBottom, nLeft, nRight
You can also declare a variable
You can also declare a variable implicitlyimplicitly by simply using its name in your script.by simply using its name in your script. That
That is not generally a good practiceis not generally a good practice because you could misspell the variablebecause you could misspell the variable name in one or more
name in one or more places, causing unexpected results when your script is run.places, causing unexpected results when your script is run. For that reason, the
For that reason, the OptionOption ExplicitExplicit statement is available to require explicitstatement is available to require explicit declaration of all variables. The
statement in your script. statement in your script. For that reason, and for
For that reason, and for coding standards proposes, it is recommended to declarecoding standards proposes, it is recommended to declare variables explicitly, and force other programmers the same by adding the Option variables explicitly, and force other programmers the same by adding the Option Explicit
Explicit statement in the head of any action, reusable action and vbs files.statement in the head of any action, reusable action and vbs files.
Option Explicit Statement
Option Explicit Statement
Forces explicit declaration of all variables in a script. Forces explicit declaration of all variables in a script. If used, the
If used, the Option ExplicitOption Explicit statement must appear in a script before any otherstatement must appear in a script before any other statements. When you use the
statements. When you use the Option ExplicitOption Explicit statement, you muststatement, you must explicitlyexplicitly declare all variables using the
declare all variables using the DimDim,, PrivatePrivate,, PublicPublic,, oror ReDimReDim statements. If youstatements. If you attempt to use an undeclared variable name, an error
attempt to use an undeclared variable name, an error occurs likeoccurs like in Figure 1 .in Figure 1 .
Figure 1 – Undefined variable e Figure 1 – Undefined variable error.rror. Tip
Tip Use
Use Option ExplicitOption Explicit to avoid incorrectly typing the name of an existing variable orto avoid incorrectly typing the name of an existing variable or to avoid confusion in code where the scope of the variable is not clear.
to avoid confusion in code where the scope of the variable is not clear. The following example illustrates use of the
The following example illustrates use of the OptionOption ExplicitExplicit statement.statement. Option Explicit
Option Explicit ' Force explicit variable declaration.' Force explicit variable declaration. Dim
Dim MyVarMyVar ' Declare variable.' Declare variable. MyInt = 10
MyInt = 10 ' Undeclared variable generates error.' Undeclared variable generates error. MyVar = 10
MyVar = 10 ' Declared variable does not generate error' Declared variable does not generate error
Working with Arrays
Working with Arrays
So far you've learned what a variable is, how to create one, and what you can So far you've learned what a variable is, how to create one, and what you can store inside one, a variable containing a single value is a scalar variable. You might store inside one, a variable containing a single value is a scalar variable. You might be wondering if there is some easy way to group variables together in a set.
be wondering if there is some easy way to group variables together in a set. you can create a variable that can contain a series of values. This is called an
you can create a variable that can contain a series of values. This is called an arrayarray variable. Array variables and scalar variables are declared in the same way, except variable. Array variables and scalar variables are declared in the same way, except that the declaration of an array variable uses parentheses ( ) following the variable that the declaration of an array variable uses parentheses ( ) following the variable name. Arrays are useful when you're storing
name. Arrays are useful when you're storing sets of similar data sets of similar data because theybecause they often make it easier to manipulate the data together. If you wanted t
often make it easier to manipulate the data together. If you wanted t o manipulateo manipulate a list of ten coordinates, you would have to execute ten different statements to a list of ten coordinates, you would have to execute ten different statements to handle each one. Besides, how can you be sure you have ten? What if you have handle each one. Besides, how can you be sure you have ten? What if you have only six at the moment? How can your code handle this kind of situation where only six at the moment? How can your code handle this kind of situation where you really don't know ahead of time how many pieces of information you have? you really don't know ahead of time how many pieces of information you have? Here is where the array
Scalar Variables and Array Variables
Scalar Variables and Array Variables
The beauty of an array is that it enables you to store and use a series of data The beauty of an array is that it enables you to store and use a series of data using one variable name and an index to distinguish the individual items. By using using one variable name and an index to distinguish the individual items. By using an index, you can often make your code simpler and more efficient so that it's an index, you can often make your code simpler and more efficient so that it's easier for you to put a script together and change it later. With
easier for you to put a script together and change it later. With VBScript,VBScript, thethe elements inside your array can hold any kind of data. The elements don't have to elements inside your array can hold any kind of data. The elements don't have to be all integers or all strings, for example. The array can hold a combination of data be all integers or all strings, for example. The array can hold a combination of data types
types
Creating Arrays
Creating Arrays
You create arrays using the same
You create arrays using the same keyword you use when creating variablkeyword you use when creating variabl es-thees-the Dim
Dim keyword. An array created with thekeyword. An array created with the DimDim keyword exists as long as thekeyword exists as long as the procedure does and is destroyed once the procedure ends.
procedure does and is destroyed once the procedure ends. If you create the arrayIf you create the array in the main script, outside the procedure, the values will persist as long as the in the main script, outside the procedure, the values will persist as long as the page is loaded.
page is loaded.
You can create two types of arrays using
You can create two types of arrays using VBScriptVBScript: fixed arrays and dynamic: fixed arrays and dynamic arrays. Fixed arrays have a
arrays. Fixed arrays have a specific number of elements in them, whereas dynamicspecific number of elements in them, whereas dynamic arrays can vary in the number of elements depending on how many are stored in arrays can vary in the number of elements depending on how many are stored in the array. Both types of arrays are useful, and both have advantages and
the array. Both types of arrays are useful, and both have advantages and disadvantages.
disadvantages.
Fixed Length Arrays
Fixed Length Arrays
In the following example, a single-dimension array containing 11 elements is In the following example, a single-dimension array containing 11 elements is declared:
declared:
Dim
Dim arrArray(10arrArray(10))
Although the number shown in the parentheses is 10, all arrays in
Although the number shown in the parentheses is 10, all arrays in VBScriptVBScript areare zero-based, so this array actually contains 11
zero-based, so this array actually contains 11 elements.elements. In a zero-based array, the number of
In a zero-based array, the number of array elements is always the nuarray elements is always the number shownmber shown in parentheses plus one.
in parentheses plus one.
This kind of array is called a fixed-size array. This kind of array is called a fixed-size array.
Dynamic Arrays
Dynamic Arrays
The second type of array you can create is the dynamic array. The benefit of a The second type of array you can create is the dynamic array. The benefit of a dynamic array is that if you don't know how large the array will be when you write dynamic array is that if you don't know how large the array will be when you write the code, you can create code that sets or changes the size while the
the code, you can create code that sets or changes the size while the VBScriptVBScript code is running. A dynamic array is created in the same way as a fixed array, but code is running. A dynamic array is created in the same way as a fixed array, but you don't put any bounds in the declaration. As a result, your statement becomes you don't put any bounds in the declaration. As a result, your statement becomes Dim
Dim arrNames()arrNames()
Eventually, you need to tell
Eventually, you need to tell VBScriptVBScript how many elements the array willhow many elements the array will contain.contain. You can do this with the
You can do this with the ReDimReDim functionfunction. ReDim. ReDim tellstells VBScriptVBScript toto "re-dimension""re-dimension" the array to however many el
the array to however many elements you specifyements you specify. ReDim. ReDim takes dimensions thetakes dimensions the same way
ReDim
ReDim arrName(nCount -arrName(nCount - 11))
So, if you enter So, if you enter ReDim
ReDim arrNames(arrNames(99))
You will create an array that has room to store ten elements. This way, you can You will create an array that has room to store ten elements. This way, you can set the size of the array while the code is running rather than when you write the set the size of the array while the code is running rather than when you write the code. This can be useful when the user gets to decide how many names he will code. This can be useful when the user gets to decide how many names he will enter
enter..
Resizing a dynamic array without Preserve.
Resizing a dynamic array without Preserve.
To use a dynamic array,
To use a dynamic array, you must subsequently useyou must subsequently use ReDimReDim to determine theto determine the number of dimensions and the size of
number of dimensions and the size of each dimension.each dimension. Dim
Dim arrMyArray()arrMyArray() ReDim
ReDim arrMyArray(arrMyArray(2525)) Redim
Redim arrArray2(arrArray2(10,10,1010,10,10))
Declares dynamic-array variables, and allocates or reallocates storage space at Declares dynamic-array variables, and allocates or reallocates storage space at procedure level.
procedure level. The
The ReDimReDim statement is used to size or resize a dynamic array that has alreadystatement is used to size or resize a dynamic array that has already been formally declared using a
been formally declared using a PrivatePrivate,, PublicPublic, or, or DimDim statement with emptystatement with empty parentheses (without dimension subscripts). You can use the
parentheses (without dimension subscripts). You can use the ReDimReDim statementstatement repeatedly to change the number of elements and dimensions in an array.
repeatedly to change the number of elements and dimensions in an array.
Resizing a dynamic array with Preserve
Resizing a dynamic array with Preserve
TheThe PreservePreserve keyword is very important when usingkeyword is very important when using ReDim.ReDim. Suppose, forSuppose, for example, that you create a dynamic array, specifying its storage space by
example, that you create a dynamic array, specifying its storage space by usingusing ReDim,
ReDim, fill it with datafill it with data, and then later decide to make it larger so you, and then later decide to make it larger so you can fill itcan fill it with more information without losing your original data.
with more information without losing your original data. In the following example
In the following example, ReDim, ReDim sets the initial size of the dynamic array to 25. Asets the initial size of the dynamic array to 25. A subsequent
subsequent ReDimReDim statement resizes the array to 30, statement resizes the array to 30, but uses thebut uses the PreservePreserve keyword to preserve the contents of the a
keyword to preserve the contents of the a rray as the resizing takes place.rray as the resizing takes place. ReDim
ReDim MyArray(MyArray(2525)) . . .
. . .
ReDim Preserve
ReDim Preserve MyArray(MyArray(3030))
There is no limit to the number of times you can resize a dynamic array, although There is no limit to the number of times you can resize a dynamic array, although if you make an array smaller, you lose the data in the eliminated elements.
if you make an array smaller, you lose the data in the eliminated elements. Figure 3
Figure 3 describes the memory allocations, when using arrays.describes the memory allocations, when using arrays.
Dim
Dim arr(5arr(5))
the system allocates 5 cells in the memory to store the array. This type of the system allocates 5 cells in the memory to store the array. This type of declaration is static; the array size
Figure 2 – Resizing static arrays Figure 2 – Resizing static arrays
Resize a dynamic array, every time you resize an array without using the keyword Resize a dynamic array, every time you resize an array without using the keyword Preserve, the system allocates a new place in the memory with the required size, Preserve, the system allocates a new place in the memory with the required size, and the last information will be lost.
and the last information will be lost.
Using the keyword preserve, the size of the array will be extended, and the Using the keyword preserve, the size of the array will be extended, and the information will not be lost
information will not be lost
Figure 3 - Memory diagram Figure 3 - Memory diagram
Array Iterations
Array Iterations
You can iterate an array using the
You can iterate an array using the For…NextFor…Next statement. The loop isstatement. The loop is based onbased on the array index
the array index
You can iterate an array using the
You can iterate an array using the For Each…NextFor Each…Next statement.statement. More information about loops in
More information about loops in Flow ControlFlow Control
VBScript Constants
VBScript Constants
Sometimes in writing code, you will want to refer to values that never change Sometimes in writing code, you will want to refer to values that never change .. TheThe values for
values for TrueTrue andand False,False, for example, are always -1 and 0, respectively. Valuesfor example, are always -1 and 0, respectively. Values that never change usually have some special meaning, such as defining
that never change usually have some special meaning, such as defining TrueTrue andand False.
False. These values that never change are called constants. The constantsThese values that never change are called constants. The constants TrueTrue and
and FalseFalse are sometimes referred to as iare sometimes referred to as implicit constants because you do notmplicit constants because you do not need to do anything to reference their constant names. They are immediately need to do anything to reference their constant names. They are immediately available in any code you write.
available in any code you write.
Working with constants
Working with constants
A constant is a variable within a program that never changes in value. Users can A constant is a variable within a program that never changes in value. Users can
create their own constants by initiali
create their own constants by initiali zing variables accordingly and then notzing variables accordingly and then not changing their value.
changing their value. VBScriptVBScript defines the specialdefines the special TrueTrue andand FalseFalse constants, asconstants, as well.
well.
When you create the simulated
When you create the simulated constant, name the constant with uppercase lettersconstant, name the constant with uppercase letters if the constant represents a value unique to your program. If the constant is a if the constant represents a value unique to your program. If the constant is a special value expected by
special value expected by VBScriptVBScript, prefix the constant name with the letters vb., prefix the constant name with the letters vb. This naming convention is not required, but it will help you distinguish the
This naming convention is not required, but it will help you distinguish the constant from all the other variables.
constant from all the other variables.
See Constant Naming Conventions on page 45 See Constant Naming Conventions on page 45
Declaring constants
Declaring constants
Constants perform a similar function to variables, in that they are a symbolic Constants perform a similar function to variables, in that they are a symbolic replacement for an item of data in memory. The difference is that a constant replacement for an item of data in memory. The difference is that a constant keeps the same value throughout its lifetime.
keeps the same value throughout its lifetime.
Constants perform a similar function to variables, in that they are a symbolic Constants perform a similar function to variables, in that they are a symbolic replacement for an item of data in memory. The difference is that a constant replacement for an item of data in memory. The difference is that a constant keeps the same value throughout its lifetime.
keeps the same value throughout its lifetime.
Values are assigned to constants using the same method used for variables, and Values are assigned to constants using the same method used for variables, and can contain the same range
can contain the same range of data subtypes. In most respects, therefore, aof data subtypes. In most respects, therefore, a constant is the same as a variable. In fact, it could be described as a va
constant is the same as a variable. In fact, it could be described as a va riableriable whose value doesn't vary! But because confusion can arise ab
whose value doesn't vary! But because confusion can arise ab out whether you areout whether you are dealing with a constant or a variable wi
dealing with a constant or a variable wi thin the script, it is safest to use a differentthin the script, it is safest to use a different naming convention for constants. The accepted method of denoting
naming convention for constants. The accepted method of denoting a constant isa constant is to use all capitals for the name. In this case, the use of underscores improves their to use all capitals for the name. In this case, the use of underscores improves their readability and is highly
readability and is highly recommended.recommended. You create user-defined constants in
You create user-defined constants in VBScriptVBScript using theusing the ConstConst statement. Usingstatement. Using the
the ConstConst statement, you can create string or statement, you can create string or numeric constants with meaningfulnumeric constants with meaningful names and assign them literal values. For example:
names and assign them literal values. For example:
Const
Const TIMEOUTTIMEOUT == 5454
Const
Const DUE_DATEDUE_DATE == #6-1-97##6-1-97#
Const
Const MY_STRING_CONSTANTMY_STRING_CONSTANT == "Hello World""Hello World"
You may want to adopt a naming
You may want to adopt a naming scheme to differentiate constants from variables.scheme to differentiate constants from variables. This will prevent you from trying to reassign constant values while your script is This will prevent you from trying to reassign constant values while your script is running. For example, you might want to use a "vb" or "con" prefix on your running. For example, you might want to use a "vb" or "con" prefix on your constant names, or you might name your constants in all capital letters. constant names, or you might name your constants in all capital letters. Differentiating constants from variables eliminates confusion as you develop Differentiating constants from variables eliminates confusion as you develop moremore complex scripts.
complex scripts. Remark
Remark
Like the constant declaration in
Like the constant declaration in VB,VB, Const inConst in VBScriptVBScript cannot be used tocannot be used to assignassign non-constant values or the values returned by
non-constant values or the values returned by VBScriptVBScript functions. This meansfunctions. This means that a statement like the following:
that a statement like the following: Const
Const LONG_INT_LEN =LONG_INT_LEN = LenLen(lNum)(lNum) '' Invalid Invalid
Is also invalid, since it attempts to assign the value of a variable to a constant. It Is also invalid, since it attempts to assign the value of a variable to a constant. It also means that a statement like:
Const
Const LONG_INT_LEN =LONG_INT_LEN = 44 + x+ x '' Invalid Invalid
Is also invalid, since it relies on the value returned by
Is also invalid, since it relies on the value returned by the VBScript Lenthe VBScript Len function.function. Finally, unlike
Finally, unlike VBVB oror VBA,VBA, you are not allowed to use any value whiyou are not allowed to use any value whi ch includes anch includes an operator in defining a constant. For example, the following declaration, which is operator in defining a constant. For example, the following declaration, which is valid in
valid in VBVB, generates a syntax error in, generates a syntax error in VBScript:VBScript: Const
Const ADDED_CONST =ADDED_CONST = 4 + 14 + 1 '' Invalid Invalid
Is also invalid, since it relies on the value returned by
Is also invalid, since it relies on the value returned by the VBScript Lenthe VBScript Len function.function. Finally, unlike
Finally, unlike VBVB oror VBAVBA,, you are not allowed to use any value whiyou are not allowed to use any value whi ch includes anch includes an operator in defining a constant. For example, the following declaration, which is operator in defining a constant. For example, the following declaration, which is valid in
valid in VBVB, generates a syntax error in, generates a syntax error in VBScriptVBScript:: Remark
Remark
Also is possible to declare non decimal values for Constants and variables specially Also is possible to declare non decimal values for Constants and variables specially hexadecimal values, that are so used in programming languages, like:
hexadecimal values, that are so used in programming languages, like:
Const
Const MY_HEXA_CONST =MY_HEXA_CONST = &H02FF&H02FF The statement is legal in
The statement is legal in VBScript,VBScript, alsoalso QuickTestQuickTest, at run-time will transfer, at run-time will transfer thethe value to 767. but there is a syntax checking bug in
value to 767. but there is a syntax checking bug in QuickTestQuickTest that will display thethat will display the follow message:
follow message:
Figure 4 - QuickTest Syntax Error Figure 4 - QuickTest Syntax Error bugbug
VBScript pre-defined constants
VBScript pre-defined constants
A number of useful constants you can use in your code are built into
A number of useful constants you can use in your code are built into VBScriptVBScript.. Constants provide a convenient way to use
Constants provide a convenient way to use specific values without actually havingspecific values without actually having to remember the value itself. Using
to remember the value itself. Using constants also makes your code moreconstants also makes your code more maintainable should the value
maintainable should the value of any constant ever change. Because theseof any constant ever change. Because these constants are already defined in
constants are already defined in VBScriptVBScript, you don't need to explicitly declare, you don't need to explicitly declare them in your code. Simply use them in place of the values they represent. them in your code. Simply use them in place of the values they represent.
Here are the various categories of constants provided in VBScript and a brief Here are the various categories of constants provided in VBScript and a brief description of each:
description of each:
Color Constants - Defines eight basic colors that
Color Constants - Defines eight basic colors that can be used in can be used in scripting.scripting. Date and Time Constants - Defines date and time constants used by various Date and Time Constants - Defines date and time constants used by various date and time functions.
date and time functions.
Date Format Constants - Defines constants used to
Date Format Constants - Defines constants used to format dates and times.format dates and times. Miscellaneous Constants - Defines constants that don't conveniently fit
Miscellaneous Constants - Defines constants that don't conveniently fit into anyinto any other category.
other category.
MsgBox Constants - Defines constants used in the
MsgBox Constants - Defines constants used in the MsgBoxMsgBox function tofunction to describedescribe button visibility, labeling, behavior, and return values.
button visibility, labeling, behavior, and return values. String Constants - Defines a vari
String Constants - Defines a variety of non-printable characters used in stringety of non-printable characters used in string manipulation.
manipulation.
Tristate Constants - Defines constants used with
Tristate Constants - Defines constants used with functions that formatfunctions that format numbers.
numbers.
VarType Constants - Defines the various Va
VarType Constants - Defines the various Va riant subtypes.riant subtypes. Note
Note
A complete listing of the constant values shown above can be found in
A complete listing of the constant values shown above can be found in VBScriptVBScript Constants topic, on the
Constants topic, on the QuickTest ProfessionalQuickTest Professional Help.Help. More information about
More information about VBScriptVBScript can be found incan be found in Error! Reference source notError! Reference source not found.
found.
The Scope and Lifetime of a Variable
The Scope and Lifetime of a Variable
A variable's scope is determined by where you declare it. When you declare a A variable's scope is determined by where you declare it. When you declare a variable within a
variable within a procedure, only code within that procedure can access or changeprocedure, only code within that procedure can access or change the value of that variable. It has local scope and is a
the value of that variable. It has local scope and is a procedure-level variable. If procedure-level variable. If you declare a variable outside a procedure, you make it recognizable to all the you declare a variable outside a procedure, you make it recognizable to all the procedures in your script. This is a
procedures in your script. This is a script-level variable, and it has script-level variable, and it has script-levelscript-level scope.
scope.
The lifetime of a variable depends on how long i
The lifetime of a variable depends on how long i t exists. The lifetime of a script-t exists. The lifetime of a script-level variable extends from the time it is declared until the time the script is level variable extends from the time it is declared until the time the script is finished running. At procedure level, a variable exists only as long as you are in finished running. At procedure level, a variable exists only as long as you are in the procedure. When the procedure exits, the varia
the procedure. When the procedure exits, the varia ble is destroyed. Local variablesble is destroyed. Local variables are ideal as t
are ideal as temporary storage space when a procedure is executing. You can emporary storage space when a procedure is executing. You can havehave local variables of the same name in several different procedures because each is local variables of the same name in several different procedures because each is recognized only by the procedure in which i
recognized only by the procedure in which i t is declared.t is declared.
Private Statement
Private Statement
DescriptionDescription The
The PrivatePrivate statement declares private variables and astatement declares private variables and a llocates storage space.llocates storage space. Declares, in a
Declares, in a ClassClass block, a private variableblock, a private variable.. Syntax
Syntax Private
Arguments Arguments
Parameter Description Parameter Description
varname
varname Name of the variable; follows standard variable naming conventions.Name of the variable; follows standard variable naming conventions. subcripts
subcripts An array and optionally specifies the number and extent oAn array and optionally specifies the number and extent o f arrayf array dimensions up to 60 multiple dimensions may be declared. dimensions up to 60 multiple dimensions may be declared.
Notes Notes
A Private variable's visibility is limited to the script in which it's created for A Private variable's visibility is limited to the script in which it's created for global variables and to the class in which it is declared for class-level
global variables and to the class in which it is declared for class-level variables. Elsewhere, the
variables. Elsewhere, the PrivatePrivate keyword generates an error.keyword generates an error. varname follows standard
varname follows standard VBVB naming conventions. It must begin with annaming conventions. It must begin with an alphabetic character, can't contain embedded periods or spaces,
alphabetic character, can't contain embedded periods or spaces, can't becan't be the same as a
the same as a VBScriptVBScript reserved word, must be shorter than 255reserved word, must be shorter than 255 characters, and must be unique within
characters, and must be unique within its scope.its scope. You can override standard variable
You can override standard variable naming conventions by placing yournaming conventions by placing your variable name in brackets. This allows you to use reserved words or illegal variable name in brackets. This allows you to use reserved words or illegal characters in variable names. For example:
characters in variable names. For example: Private
Private [me][me] Private
Private [1Var][1Var] Private
Private [2-Var][2-Var] Private
Private [Left][Left]
Using the subscripts argument, you can declare up to 60 multiple Using the subscripts argument, you can declare up to 60 multiple dimensions for the array
dimensions for the array..
If the subscripts argument isn't used (i.e., the variable name is followed by If the subscripts argument isn't used (i.e., the variable name is followed by empty parentheses), the array is declared dynami
empty parentheses), the array is declared dynami c. You can change bothc. You can change both the number of dimensions and the number of elements of a dynamic array the number of dimensions and the number of elements of a dynamic array using the
using the ReDimReDim statementstatement.. In
In QuickTest,QuickTest, thethe Public/PrivatePublic/Private Scopes are ignored. Any variable youScopes are ignored. Any variable you declare inside a reusable action will remain
declare inside a reusable action will remain Private.Private. Tips
Tips
All variables created at procedure level (that is, in code within a
All variables created at procedure level (that is, in code within a Sub...EndSub...End Sub, Function...End Function,
Sub, Function...End Function, oror PropertyProperty...EndEnd PropertyProperty construct areconstruct are local by default. That is, they don't have scope outside the procedure in local by default. That is, they don't have scope outside the procedure in which they are created. The use of the
which they are created. The use of the PrivatePrivate keyword in these caseskeyword in these cases generates a runtime error.
generates a runtime error.
You cannot change the dimensions of arrays that were defined to be You cannot change the dimensions of arrays that were defined to be dynamic arrays while preserving their original data.
dynamic arrays while preserving their original data. It's good practice to always use
It's good practice to always use Option ExplicitOption Explicit at the beginning of aat the beginning of a module to prevent misnamed variables from causi
module to prevent misnamed variables from causi ng hard-to-find errors.ng hard-to-find errors.
Public Statement
Public Statement
DescriptionThe
The PublicPublic statement declares public variables and allocatesstatement declares public variables and allocates storagestorage space.space. Declares, in a
Declares, in a ClassClass block, a private variable.block, a private variable. Syntax
Syntax
Public
Public varnamevarname[([[([subscriptssubscripts])][,])][, varnamevarname[([[([subscriptssubscripts])]] . . .])]] . . . Arguments
Arguments
Parameter Description Parameter Description
varname
varname Name of the variable; follows standard variable naming conventions.Name of the variable; follows standard variable naming conventions. subcripts
subcripts An array and optionally specifies the number and extent oAn array and optionally specifies the number and extent o f arrayf array dimensions up to 60 multiple dimensions may be declared. dimensions up to 60 multiple dimensions may be declared.
Notes Notes
The behavior of a
The behavior of a PublicPublic variable depends on where it's declared, as thevariable depends on where it's declared, as the following table shows
following table shows Variable
Variable declared declared in... in... ScopeScope
Any procedure, Function or Property Any procedure, Function or Property statement
statement
Illegal; generates a syntax error; use the Dim Illegal; generates a syntax error; use the Dim statement instead.
statement instead. Global
Global code code (in (in external external vbs vbs file file ) ) Variable Variable is is available available throughout throughout the the script.script. Global code (in a reusable action )
Global code (in a reusable action ) Variable is available throughout the ReusableVariable is available throughout the Reusable action only (Private).
action only (Private). Class block declarations section
Class block declarations section Variable is available as a property of the class toVariable is available as a property of the class to all code within the script.
all code within the script.
varname
varname follows standard VB naming conventions. It must begin with anfollows standard VB naming conventions. It must begin with an alphabetic character, can't contain embedded periods or spaces,
alphabetic character, can't contain embedded periods or spaces, can't becan't be the same as a VBScript reserved word, must be shorter than 255
the same as a VBScript reserved word, must be shorter than 255 characters, and must be unique withi
characters, and must be unique within its scope.n its scope. You can override standard variable
You can override standard variable naming conventions by placing yournaming conventions by placing your variable name in brackets. This allows you to use reserved words or illegal variable name in brackets. This allows you to use reserved words or illegal characters in variable names. For example:
characters in variable names. For example: Public
Public [me][me] Public
Public [1Var][1Var] Public
Public [2-Var][2-Var] Public
Public [Left][Left]
Using the subscripts argument, you can declare up to 60 multiple Using the subscripts argument, you can declare up to 60 multiple dimensions for the array.
dimensions for the array.
If the subscripts argument isn't used (i.e., the variable name is followed by If the subscripts argument isn't used (i.e., the variable name is followed by empty parentheses), the array is declared dynami
empty parentheses), the array is declared dynami c. You can change bothc. You can change both the number of dimensions and the number of elements of a dynamic array the number of dimensions and the number of elements of a dynamic array using the
using the ReDimReDim statementstatement.. In
In QuickTest, the Public/PrivateQuickTest, the Public/Private ScopesScopes are ignored. Any variableare ignored. Any variable youyou declare inside a reusable action will remain
declare inside a reusable action will remain Private.Private. Tips
Instead of declaring a variable as
Instead of declaring a variable as PublicPublic within a class construct, youwithin a class construct, you should create
should create Property LetProperty Let andand Property GetProperty Get procedures that assignprocedures that assign andand retrieve the value of a private variable, respectively.
retrieve the value of a private variable, respectively.
You cannot change the dimensions of arrays that were defined to be You cannot change the dimensions of arrays that were defined to be dynamic arrays while preserving their original data.
dynamic arrays while preserving their original data. It's good practice to always use
It's good practice to always use Option ExplicitOption Explicit at the beginning of aat the beginning of a module to prevent misnamed variables from causi
module to prevent misnamed variables from causi ng hard-to-find errors.ng hard-to-find errors. To use a global variable, which is not recommended, you can use a
To use a global variable, which is not recommended, you can use a PublicPublic MyVar
MyVar statement on an externalstatement on an external vbsvbs file.file.
To use global variables in your testing suite, use the Environment object, To use global variables in your testing suite, use the Environment object, or/and the global datasheet or a global dictionary pre-defined in the or/and the global datasheet or a global dictionary pre-defined in the repository. For more information see:
repository. For more information see:
QuickTest Professional User's Guide > Creating Tests or Components > Working with Actions > QuickTest Professional User's Guide > Creating Tests or Components > Working with Actions > Sharing Action Information > Sharing Values Using
Sharing Action Information > Sharing Values Using the Dictionary Object the Dictionary Object
VBScript Operators
VBScript Operators
Arithmetic Operators Arithmetic Operators
Operators used to perform mathematical calculations. Operators used to perform mathematical calculations. Assignment Operator
Assignment Operator
Operator used to assign a value to a property or variable. Operator used to assign a value to a property or variable. Comparison Operators
Comparison Operators Operators used to p
Operators used to perform comparisons.erform comparisons. Concatenation Operators
Concatenation Operators
Operators used to combine strings. Operators used to combine strings. Logical Operators
Logical Operators
Operators used to perform logical
Operators used to perform logical operations.operations.
Working with Operators
Working with Operators
As you begin to writeAs you begin to write VBScriptVBScript code, you will use operators so much that theircode, you will use operators so much that their use will become natural to you. In this section, you will learn about each of the use will become natural to you. In this section, you will learn about each of the operators available to you in
operators available to you in VBScriptVBScript, as well as how you might go about using, as well as how you might go about using them.
them.
When several operations occur in an expression, each part i
When several operations occur in an expression, each part i s evaluated ands evaluated and resolved in a predetermined order called operator precedence. You
resolved in a predetermined order called operator precedence. You can usecan use parentheses to override the order of precedence and force some
parentheses to override the order of precedence and force some parts of anparts of an expression to be evaluated before others. Operati
expression to be evaluated before others. Operati ons within parentheses areons within parentheses are always performed before those outside. Within
always performed before those outside. Within parentheses, however, standardparentheses, however, standard operator precedence is maintained.
operator precedence is maintained.
When expressions contain operators from more than one category, arithmetic When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next,
operators are evaluated first, comparison operators are evaluated next, and logicaland logical operators are evaluated last. Comparison operators all
operators are evaluated last. Comparison operators all have equal precedence;have equal precedence; that is, they are evaluated in the left-to-right order in which they appear.
that is, they are evaluated in the left-to-right order in which they appear. Arithmetic and logical operators are evaluated in the following order of Arithmetic and logical operators are evaluated in the following order of precedence.
Arithmetic Operators
Arithmetic Operators
The first major class of
The first major class of operators is arithmetic operators. Arithmetic operatorsoperators is arithmetic operators. Arithmetic operators enable you to perform simple
enable you to perform simple arithmetic on one or more variables. Most of arithmetic on one or more variables. Most of thesethese operators will be familiar to you because you have been exposed to them in operators will be familiar to you because you have been exposed to them in everyday life. Few people will be surprised to find, for example, that the + everyday life. Few people will be surprised to find, for example, that the + operator performs addition! Some operators, however, might be new
operator performs addition! Some operators, however, might be new to you. Into you. In any case, you need to understand how to apply these operators to variables and any case, you need to understand how to apply these operators to variables and literals in
literals in VBScriptVBScript code.code.
Operators fit into three separate categories: arithmetic
Operators fit into three separate categories: arithmetic operators, comparisonoperators, comparison operators, and logical operators. Each of these
operators, and logical operators. Each of these categories has a special use in categories has a special use in aa VBScript program. Operators are executed in a
VBScript program. Operators are executed in a specific order when they arespecific order when they are combined. Programmers must take this order into account when they
combined. Programmers must take this order into account when they write code.write code.
Description Symbol Description Symbol Addition Addition ++ Subtraction Subtraction --Multiplication Multiplication ** Division Division / / Integer Division Integer Division \ \ Exponentiation Exponentiation ^^ Modulus arithmetic
Modulus arithmetic ModMod Unary negation
Unary negation --String concatenation String concatenation & &
Table 1 - Arithmetic operators Table 1 - Arithmetic operators
Addition (+)
Addition (+)
The first arithmetic operator is the addition operator. You already used this The first arithmetic operator is the addition operator. You already used this operator yesterday and probably intuitively understood its purpose because it operator yesterday and probably intuitively understood its purpose because it is sois so commonly used and easy to understand. The addition operator is used to add commonly used and easy to understand. The addition operator is used to add values, whether they are stored in
values, whether they are stored in variables, constants, or literal numbers. Youvariables, constants, or literal numbers. You also use the +
also use the + operator to concatenate strings.operator to concatenate strings.
Subtraction (-)
Subtraction (-)
This operator works the same way the addition operator does except that it This operator works the same way the addition operator does except that it subtracts one or more numbers rather than add
subtracts one or more numbers rather than add them. Otherwise, the syntax is thethem. Otherwise, the syntax is the same.
same.
Multiplication (*)
Multiplication (*)
Addition and subtraction are important, but you also need to be able to multiply Addition and subtraction are important, but you also need to be able to multiply values together. In most computer languages, the
values together. In most computer languages, the ** symbol is used to indicatesymbol is used to indicate multiplication, not the x symbol.
Division (/) and Integer Division (\)
Division (/) and Integer Division (\)
The division operator is the
The division operator is the last of the four last of the four commonly used arithmetic operators.commonly used arithmetic operators. Among the common arithmetic operators, division is the
Among the common arithmetic operators, division is the most complicatedmost complicated arithmetic operation a computer performs.
arithmetic operation a computer performs. VBScript has two types of
VBScript has two types of division operators. The first operator handles numbersdivision operators. The first operator handles numbers with decimal points. Usually referred to as the floating-point division operator, it's with decimal points. Usually referred to as the floating-point division operator, it's represented by the / symbol in
represented by the / symbol in code listings.code listings.
The floating-point division operator is designed to divide values with decimal The floating-point division operator is designed to divide values with decimal points, but it can also divide numbers without decimals.
points, but it can also divide numbers without decimals.
Exponentiation (^)
Exponentiation (^)
Raises a number to the power of an exponent. Raises a number to the power of an exponent.
Modulus Arithmetic (Mod)
Modulus Arithmetic (Mod)
The Mod operator is another pThe Mod operator is another powerful arithmetic operator. Essentially, the Modowerful arithmetic operator. Essentially, the Mod operator returns the remainder after dividing
operator returns the remainder after dividing one number into another.one number into another.
Unary Negation (-)
Unary Negation (-)
The last of the arithmetic operators is the negation operator. Simply put, this The last of the arithmetic operators is the negation operator. Simply put, this operator changes the sign of a value contained in a variable or creates a negative operator changes the sign of a value contained in a variable or creates a negative number.
number.
String Concatenation (&)(+)
String Concatenation (&)(+)
Forces string concatenation of two expressions. Forces string concatenation of two expressions.
You use the string concatenation operator to merge tw
You use the string concatenation operator to merge two strings together.o strings together.
Comparison Operators
Comparison Operators
The first set of operatorsThe first set of operators VBScriptVBScript provides are arithmetic operators. This sectionprovides are arithmetic operators. This section discusses the second type: comparison operators. As the name implies, you use discusses the second type: comparison operators. As the name implies, you use comparison operators to compare one or more variables, numbers, constants, or a comparison operators to compare one or more variables, numbers, constants, or a combination of the three.
combination of the three. VBScriptVBScript has many different types of comparisonhas many different types of comparison operators, and each check for a di
operators, and each check for a different comparison condition.fferent comparison condition.
Description Symbol Description Symbol Equality Equality == Inequality Inequality <><> Less than Less than << Greater than Greater than >> Less than or equal to
Less than or equal to <=<= Greater than or equal to
Object equivalence
Object equivalence IsIs
Table 2 - Comparison
Table 2 - Comparison OperatorsOperators
Equality (=)
Equality (=)
You use the equality operator to see if a variable, constant, or number is equal to You use the equality operator to see if a variable, constant, or number is equal to another. It's common to mistake the equali
another. It's common to mistake the equali ty operator for the assignmentty operator for the assignment operator, which is also represented by an
operator, which is also represented by an equal sign. You use the aequal sign. You use the assignmentssignment operator to set a variable equal to another variable, number, string, constant, or operator to set a variable equal to another variable, number, string, constant, or other data entity. For comparing
other data entity. For comparing strings use thestrings use the StrCompStrComp function.function.
Inequality (<>)
Inequality (<>)
Another important comparison operator is the inequality operator. You
Another important comparison operator is the inequality operator. You use thisuse this operator to test whether a variable is not equal to another variable or some data operator to test whether a variable is not equal to another variable or some data element. For comparing strings use the
element. For comparing strings use the StrCompStrComp function.function.
Less Than (<) and Greater Than (>)
Less Than (<) and Greater Than (>)
You might have a condition where you don't care whether a variable is equal to You might have a condition where you don't care whether a variable is equal to another, but you do want to know whether it is greater than or less than another another, but you do want to know whether it is greater than or less than another variable, number, or constant. In such a
variable, number, or constant. In such a case, you need the greater-than and lcase, you need the greater-than and l ess- ess-than operators. For comparing strings use the
than operators. For comparing strings use the StrCompStrComp function.function.
Less than or equal (<=), greater than or equal to (>=)
Less than or equal (<=), greater than or equal to (>=)
Sometimes, you also might want to see whether a variable is greater than
Sometimes, you also might want to see whether a variable is greater than or equal or equal to
to some other variable, constant, or number. Perhaps you want to know if it issome other variable, constant, or number. Perhaps you want to know if it is lessless than or equal to
than or equal to the entity. Then, you can the entity. Then, you can combine operators to use the less-than-combine operators to use the less-than-or-equal and greater-than-less-than-or-equal operators,
or-equal and greater-than-or-equal operators, <=<= andand >=>=.. For comparing strings use the
For comparing strings use the StrCompStrComp function.function.
Object Equivalence (Is)
Object Equivalence (Is)
The last comparison operator is designed
The last comparison operator is designed for objects.for objects. This operator does not compare one object
This operator does not compare one object to another, nor does it to another, nor does it compare values.compare values. This special operator simply checks to see if the two object references in the
This special operator simply checks to see if the two object references in the expression refer to the same object. Suppose, f
expression refer to the same object. Suppose, f or example, you have assigned aor example, you have assigned a command button in your script. You have
command button in your script. You have another variable,another variable, myObject myObject that is set tothat is set to reference different objects at different points i
reference different objects at different points i n your program. Assume that an your program. Assume that a statement has been carried out that assigns the variable
statement has been carried out that assigns the variable myObject myObject to referenceto reference this button
this button
Logical Operators
Logical Operators
The last category of operators in
The last category of operators in VBScriptVBScript is logical operators. The logicalis logical operators. The logical operators might require a more significant
operators might require a more significant amount of understanding to appreciate.amount of understanding to appreciate. In some cases, the way
intuitive thinking. If you've ever taken a
intuitive thinking. If you've ever taken a course in logic, you have first-handcourse in logic, you have first-hand experience with this.
experience with this.
Because logical operators are such an important part
Because logical operators are such an important part of of VBScriptVBScript in particular,in particular, and every programming language in general, it's important to gain a good and every programming language in general, it's important to gain a good understanding, starting with the basics, so that
understanding, starting with the basics, so that you can use them effectively.you can use them effectively.
Description Symbol
Description Symbol
Logical negation
Logical negation NotNot Logical conjunction
Logical conjunction AndAnd Logical disjunction
Logical disjunction OrOr Logical exclusion
Logical exclusion XorXor Logical equivalence
Logical equivalence EqvEqv Logical implication
Logical implication ImpImp
Table 3 - Logical
Table 3 - Logical OperatorsOperators
Logical Negation (Not)
Logical Negation (Not)
The operator performs logical negation on a
The operator performs logical negation on a n expression. In addition, the Notn expression. In addition, the Not operator inverts the bit values of any variable and sets the corresponding bit operator inverts the bit values of any variable and sets the corresponding bit This operator has the following results
This operator has the following results If
If Expression Expression is is Then Then result result isis
True False True False False True False True Null Null Null Null Bit
Bit Expression Expression is is Bit Bit Result Result isis
0
0 11
1
1 00
Table 4 - Logical Negation Table 4 - Logical Negation
Logical Conjunction (And)
Logical Conjunction (And)
The operator performs a logical
The operator performs a logical conjunction on two expressions.conjunction on two expressions. In order to obtain
In order to obtain TrueTrue in the result variable, bothin the result variable, both expression1expression1 andand expression2expression2 must be
must be TrueTrue. You often use this operator to make sure two or more conditions. You often use this operator to make sure two or more conditions are true before performing some action.
are true before performing some action. If
If Expression1 Expression1 is is And And Expression2 Expression2 is is Then result Then result isis
True
True True True TrueTrue
True
True False False FalseFalse False
False True True FalseFalse False
False False False FalseFalse
If
0 0 0 0 00 0 0 1 1 00 1 1 0 0 00 1 1 1 1 11 Table 5 - Logical
Table 5 - Logical conjuctionconjuction
Logical Disjunction (Or)
Logical Disjunction (Or)
The operator performs a logicalThe operator performs a logical disjunction on two expressions.disjunction on two expressions. If either or both expressions evaluate to
If either or both expressions evaluate to TrueTrue,, result result isis TrueTrue.. The
The OrOr operator also performs a bitwise comparison of identically positioned bits inoperator also performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in
two numeric expressions and sets the corresponding bit in result.result. If
If Expression1 Expression1 is is And And Expression2 Expression2 is is Then result Then result isis
True
True True True TrueTrue
True
True False False TrueTrue False
False True True TrueTrue False
False False False FalseFalse
If
If bit bit in in expression1 expression1 is is and and bit bit in in expression2 expression2 is is Then Then result result isis
0 0 0 0 00 0 0 1 1 11 1 1 0 0 11 1 1 1 1 11
Table 6 – Logical Disjunction Table 6 – Logical Disjunction
Logical Exclusion (Xor)
Logical Exclusion (Xor)
The operator performs a logicalThe operator performs a logical exclusion on two expressions.exclusion on two expressions.
The exclusion operator is another in the family of logical operators that you can The exclusion operator is another in the family of logical operators that you can use to make decisions based on the
use to make decisions based on the contents of one or more expressions. It checkscontents of one or more expressions. It checks whether one and only one conditi
whether one and only one condition is exclusivelyon is exclusively TrueTrue.. If
If Expression1 Expression1 is is And And Expression2 Expression2 is is Then result Then result isis
True
True True True FalseFalse True
True False False TrueTrue False
False True True TrueTrue False
False False False FalseFalse
If
If bit bit in in expression1 expression1 is is and and bit bit in in expression2 expression2 is is Then Then result result isis
0 0 0 0 00 0 0 1 1 11 1 1 0 0 11