Page 1
VBScript Basics
Page 1 of 52
Chapter 03
Page 2
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 2 of 52
Chapter 03
Page 3
What is a variable?
A variable is a virtual container in the computer's memory or convenient
placeholder that refers to a computer memory location where you can store
program information that may change during the time your script is running.
Where the variable is stored in computer memory is unimportant. What is
important is that you only have to refer to a variable by name to see or change its
value. In VBScript, variables are always of one fundamental data type, Variant.
A computer program can store information in a variable and then access that
information later by referring to the variable's name.
VBScript Basics
Page 3 of 52
Chapter 03
Page 4
Syntax
Dim varname[([subscripts])][, varname[([subscripts])]] . . .
Arguments
Parameter
Description
varname
subcripts
Notes
When variables are first initialized with the Dim statement, they have a
value of Empty. In addition, if a variable has been initialized but not
assigned a value, the following expressions will both evaluate to True:
If vVar = 0 Then
If vVar = "" Then
You declare variables explicitly in your script using the Dim statement, the
Public statement, and the Private statement.
Dim nDegreesFahrenheit
You declare multiple variables by separating each variable name with a comma.
Dim nTop, nBottom, nLeft, nRight
You can also declare a variable implicitly by simply using its name in your script.
That is not generally a good practice because you could misspell the variable
name in one or more places, causing unexpected results when your script is run.
For that reason, the Option Explicit statement is available to require explicit
declaration of all variables. The Option Explicit statement should be the first
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 4 of 52
Chapter 03
Page 5
'
'
'
'
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 5 of 52
Chapter 03
Page 6
Creating Arrays
You create arrays using the same keyword you use when creating variables-the
Dim keyword. An array created with the Dim keyword exists as long as the
procedure does and is destroyed once the procedure ends. If you create the array
in the main script, outside the procedure, the values will persist as long as the
page is loaded.
You can create two types of arrays using VBScript: fixed arrays and dynamic
arrays. Fixed arrays have a specific number of elements in them, whereas dynamic
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
disadvantages.
Dynamic Arrays
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
the code, you can create code that sets or changes the size while the VBScript
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
Dim arrNames()
Eventually, you need to tell VBScript how many elements the array will contain.
You can do this with the ReDim function. ReDim tells VBScript to "re-dimension"
the array to however many elements you specify. ReDim takes dimensions the
same way Dim can. The syntax is
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 6 of 52
Chapter 03
Page 7
ReDim arrName(nCount - 1)
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
code. This can be useful when the user gets to decide how many names he will
enter.
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.
Figure 3 describes the memory allocations, when using arrays.
Dim arr(5)
the system allocates 5 cells in the memory to store the array. This type of
declaration is static; the array size cannot be changed.
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 7 of 52
Chapter 03
Page 8
Array Iterations
You can iterate an array using the ForNext statement. The loop is based on
the array index
You can iterate an array using the For EachNext statement.
More information about loops in Flow Control
VBScript Constants
Sometimes in writing code, you will want to refer to values that never change. The
values for True and False, for example, are always -1 and 0, respectively. Values
that never change usually have some special meaning, such as defining True and
False. These values that never change are called constants. The constants True
and False are sometimes referred to as implicit constants because you do not
need to do anything to reference their constant names. They are immediately
available in any code you write.
VBScript Basics
Page 8 of 52
Chapter 03
Page 9
create their own constants by initializing variables accordingly and then not
changing their value. VBScript defines the special True and False constants, as
well.
When you create the simulated constant, name the constant with uppercase letters
if the constant represents a value unique to your program. If the constant is a
special value expected by VBScript, prefix the constant name with the letters vb.
This naming convention is not required, but it will help you distinguish the
constant from all the other variables.
See Constant Naming Conventions on page 45
Declaring constants
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
keeps the same value throughout its lifetime.
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
keeps the same value throughout its lifetime.
Values are assigned to constants using the same method used for variables, and
can contain the same range of data subtypes. In most respects, therefore, a
constant is the same as a variable. In fact, it could be described as a variable
whose value doesn't vary! But because confusion can arise about whether you are
dealing with a constant or a variable within the script, it is safest to use a different
naming convention for constants. The accepted method of denoting a constant is
to use all capitals for the name. In this case, the use of underscores improves their
readability and is highly recommended.
You create user-defined constants in VBScript using the Const statement. Using
the Const statement, you can create string or numeric constants with meaningful
names and assign them literal values. For example:
Const TIMEOUT = 54
Const DUE_DATE = #6-1-97#
Const MY_STRING_CONSTANT = "Hello World"
You may want to adopt a naming scheme to differentiate constants from variables.
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
constant names, or you might name your constants in all capital letters.
Differentiating constants from variables eliminates confusion as you develop more
complex scripts.
Remark
Like the constant declaration in VB, Const in VBScript cannot be used to assign
non-constant values or the values returned by VBScript functions. This means
that a statement like the following:
Const LONG_INT_LEN = Len(lNum)
' Invalid
VBScript Basics
Page 9 of 52
Chapter 03
Const LONG_INT_LEN = 4 + x
Page 10
' Invalid
Is also invalid, since it relies on the value returned by the VBScript Len function.
Finally, unlike VB or VBA, you are not allowed to use any value which includes an
operator in defining a constant. For example, the following declaration, which is
valid in VB, generates a syntax error in VBScript:
Const ADDED_CONST = 4 + 1
' Invalid
Is also invalid, since it relies on the value returned by the VBScript Len function.
Finally, unlike VB or VBA, you are not allowed to use any value which includes an
operator in defining a constant. For example, the following declaration, which is
valid in VB, generates a syntax error in VBScript:
Remark
Also is possible to declare non decimal values for Constants and variables specially
hexadecimal values, that are so used in programming languages, like:
Const MY_HEXA_CONST = &H02FF
The statement is legal in VBScript, also QuickTest, at run-time will transfer the
value to 767. but there is a syntax checking bug in QuickTest that will display the
follow message:
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 10 of 52
Chapter 03
Page 11
Here are the various categories of constants provided in VBScript and a brief
description of each:
Color Constants - Defines eight basic colors that can be used in scripting.
Date and Time Constants - Defines date and time constants used by various
date and time functions.
Date Format Constants - Defines constants used to format dates and times.
Miscellaneous Constants - Defines constants that don't conveniently fit into any
other category.
MsgBox Constants - Defines constants used in the MsgBox function to describe
button visibility, labeling, behavior, and return values.
String Constants - Defines a variety of non-printable characters used in string
manipulation.
Tristate Constants - Defines constants used with functions that format
numbers.
VarType Constants - Defines the various Variant subtypes.
Note
A complete listing of the constant values shown above can be found in VBScript
Constants topic, on the QuickTest Professional Help.
More information about VBScript can be found in Error! Reference source not
found.
Private Statement
Description
The Private statement declares private variables and allocates storage space.
Declares, in a Class block, a private variable.
Syntax
Private varname[([subscripts])][, varname[([subscripts])]] . . .
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 11 of 52
Chapter 03
Page 12
Arguments
Parameter
Description
varname
subcripts
Notes
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
variables. Elsewhere, the Private keyword generates an error.
varname follows standard VB naming conventions. It must begin with an
alphabetic character, can't contain embedded periods or spaces, can't be
the same as a VBScript reserved word, must be shorter than 255
characters, and must be unique within its scope.
You can override standard variable naming conventions by placing your
variable name in brackets. This allows you to use reserved words or illegal
characters in variable names. For example:
Private [me]
Private [1Var]
Private [2-Var]
Private [Left]
Using the subscripts argument, you can declare up to 60 multiple
dimensions for the array.
If the subscripts argument isn't used (i.e., the variable name is followed by
empty parentheses), the array is declared dynamic. You can change both
the number of dimensions and the number of elements of a dynamic array
using the ReDim statement.
In QuickTest, the Public/Private Scopes are ignored. Any variable you
declare inside a reusable action will remain Private.
Tips
All variables created at procedure level (that is, in code within a Sub...End
Sub, Function...End Function, or Property...End Property construct are
local by default. That is, they don't have scope outside the procedure in
which they are created. The use of the Private keyword in these cases
generates a runtime error.
You cannot change the dimensions of arrays that were defined to be
dynamic arrays while preserving their original data.
It's good practice to always use Option Explicit at the beginning of a
module to prevent misnamed variables from causing hard-to-find errors.
Public Statement
Description
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 12 of 52
Chapter 03
Page 13
The Public statement declares public variables and allocates storage space.
Declares, in a Class block, a private variable.
Syntax
Public varname[([subscripts])][, varname[([subscripts])]] . . .
Arguments
Parameter
Description
varname
subcripts
Notes
The behavior of a Public variable depends on where it's declared, as the
following table shows
Variable declared in...
Scope
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 13 of 52
Chapter 03
Page 14
VBScript Operators
Arithmetic Operators
Operators used to perform mathematical calculations.
Assignment Operator
Operator used to assign a value to a property or variable.
Comparison Operators
Operators used to perform comparisons.
Concatenation Operators
Operators used to combine strings.
Logical Operators
Operators used to perform logical operations.
VBScript Basics
Page 14 of 52
Chapter 03
Page 15
Arithmetic Operators
The first major class of operators is arithmetic operators. Arithmetic operators
enable you to perform simple arithmetic on one or more variables. Most of these
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 +
operator performs addition! Some operators, however, might be new to you. In
any case, you need to understand how to apply these operators to variables and
literals in VBScript code.
Operators fit into three separate categories: arithmetic operators, comparison
operators, and logical operators. Each of these categories has a special use in a
VBScript program. Operators are executed in a specific order when they are
combined. Programmers must take this order into account when they write code.
Description
Symbol
Addition
Subtraction
Multiplication
Division
Integer Division
Exponentiation
Modulus arithmetic
Mod
Unary negation
String concatenation
&
Addition (+)
The first arithmetic operator is the addition operator. You already used this
operator yesterday and probably intuitively understood its purpose because it is so
commonly used and easy to understand. The addition operator is used to add
values, whether they are stored in variables, constants, or literal numbers. You
also use the + operator to concatenate strings.
Subtraction (-)
This operator works the same way the addition operator does except that it
subtracts one or more numbers rather than add them. Otherwise, the syntax is the
same.
Multiplication (*)
Addition and subtraction are important, but you also need to be able to multiply
values together. In most computer languages, the * symbol is used to indicate
multiplication, not the x symbol.
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 15 of 52
Chapter 03
Page 16
Exponentiation (^)
Raises a number to the power of an exponent.
Comparison Operators
The first set of operators VBScript provides are arithmetic operators. This section
discusses the second type: comparison operators. As the name implies, you use
comparison operators to compare one or more variables, numbers, constants, or a
combination of the three. VBScript has many different types of comparison
operators, and each check for a different comparison condition.
Description
Symbol
Equality
Inequality
<>
Less than
<
Greater than
>
<=
>=
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 16 of 52
Chapter 03
Object equivalence
Page 17
Is
Equality (=)
You use the equality operator to see if a variable, constant, or number is equal to
another. It's common to mistake the equality operator for the assignment
operator, which is also represented by an equal sign. You use the assignment
operator to set a variable equal to another variable, number, string, constant, or
other data entity. For comparing strings use the StrComp function.
Inequality (<>)
Another important comparison operator is the inequality operator. You use this
operator to test whether a variable is not equal to another variable or some data
element. For comparing strings use the StrComp function.
Logical Operators
The last category of operators in VBScript is logical operators. The logical
operators might require a more significant amount of understanding to appreciate.
In some cases, the way you use logical operators seems to run counter to your
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 17 of 52
Chapter 03
Page 18
intuitive thinking. If you've ever taken a course in logic, you have first-hand
experience with this.
Because logical operators are such an important part of VBScript in particular,
and every programming language in general, it's important to gain a good
understanding, starting with the basics, so that you can use them effectively.
Description
Symbol
Logical negation
Not
Logical conjunction
And
Logical disjunction
Or
Logical exclusion
Xor
Logical equivalence
Eqv
Logical implication
Imp
Then result is
True
False
False
True
Null
Null
Bit Expression is
Bit Result is
And Expression2 is
Then result is
True
True
True
True
False
False
False
True
False
False
False
False
If bit in expression1 is
Then result is
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 18 of 52
Chapter 03
Page 19
And Expression2 is
Then result is
True
True
True
True
False
True
False
True
True
False
False
False
If bit in expression1 is
Then result is
And Expression2 is
Then result is
True
True
False
True
False
True
False
True
True
False
False
False
If bit in expression1 is
Then result is
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 19 of 52
Chapter 03
Page 20
And Expression2 is
Then result is
True
True
True
True
False
False
False
True
False
False
False
True
If bit in expression1 is
Then result is
And Expression2 is
Then result is
True
True
True
True
False
True
False
True
False
False
False
True
If bit in expression1 is
Then result is
VBScript Basics
Page 20 of 52
Chapter 03
Page 21
Flow Control
Controlling the Flow of VBScript Code
Both variables and operators are fundamental building blocks you need to
understand to write useful code. This subject is very important when you want
your programs to make on the spot decisions or execute differently based on what
the user wants to do.
You will learn all the VBScript control structures and see several examples of how
they can be applied. You will also learn which structures are more applicable and
more useful under which situations. You'll learn not only how to control the flow of
code, but also how best to do so.
Once you've learned how to control the flow of code within a procedure, you'll see
how you can control the flow of code within the entire application.
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 21 of 52
Chapter 03
Page 22
Description
Executes a statement or block of statements based on the Boolean (True or
False) value of an expression.
Syntax
If condition Then statements [Else elsestatements ]
If condition Then
[statements]
[ElseIf condition-n Then
[elseifstatements] ...
[Else
[elsestatements]]
End If
Arguments
Argument
Description
condition
statements
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 22 of 52
Chapter 03
Page 23
condition-n
Same as condition.
elseifstatements
elsestatements
IfThen
The first control structure you should know about is IfThen. The syntax for this
control structure is given as
If condition = True Then
... the code that executes if the condition is satisfied
End If
Where condition is some test you want to apply to the conditional structure. If the
condition is true, the code within the If and End If statements is executed. If the
condition is not true, the code within these statements is skipped over and does
not get executed.
Suppose you have a Boolean variable named bShowDetails. This variable is set to
True at some point in your code if the user wants to see the specific details of a
calculation. You could set up a simple conditional statement that gives the user the
help he or she needs by entering:
If bShowDetail Then MsgBox "More details. . . "
This way, if the user doesn't want to see the details and the variable hasn't been
set previously, the code in between the two statements is ignored. The condition
expression is typically a test, such as whether one variable is equal to another or
whether a variable equals a certain value. The condition always comes out either
True or False, but the conditional structure only executes the code within it if the
condition is True. When using an IfThen structure, make sure your condition is
expressed properly.
To run only one statement when a condition is True, use the single-line syntax
for the If...Then...Else statement.
To run more than one line of code, you must use the multiple-line (or block)
syntax. This syntax includes the End If statement, as shown in the following
example:
sMsg = "Either you're not born yet or you're getting too old for this stuff!"
If nAge <= 0 Or nAge > 120 Then
MsgBox sMsg
bFail = True
End If
IfThen...Else
The IfThen structure is quite useful, but it has one limitation. Oftentimes, when
people make decisions, they want to do one thing if a condition is true; otherwise,
they want to do something different.
For example, you may have imagined a simple decision structure in your mind that
if your favorite restaurant is opens; you will go there to eat. Otherwise, you will go
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 23 of 52
Chapter 03
Page 24
home and cook your own meal. You're certain to carry out either one of the two
options because you're hungry, it's time for dinner, and hey-you deserve it after
an afternoon of programming.
Apply this decision process to some code. Assume you had a variable that was
previously set to indicate the state of whether your favorite restaurant is open or
closed based on the time a script is run. You want to have your code check this
variable and put up a message box to let you know whether you can hit your
favorite restaurant. In this case, you wouldn't want to use the logic.
If MyFavoriteRestaurantOpen = True Then
Msgbox "Go To My Favorite Restaurant!"
End If
Because that leaves out the alternative. You could use two statements:
If MyFavoriteRestaurantOpen = True Then
Msgbox "Go To My Favorite Restaurant!"
End If
If MyFavoriteRestaurantOpen = False Then
Msgbox "Go Home and Cook!"
End If
But wouldn't it be nice if you didn't have to repeat the test where you check the
negative instead of positive condition? Fortunately, you have another control
structure available to you in VBScript that makes this process easier. The control
structure, called IfThenElse, is represented as:
If condition = True Then
...this is the code that executes if the condition is satisfied
Else
...this is the code that executes if the condition is not satisfied
End If
You could enter the expression you've formed in your mind as you drive toward My
Favorite Restaurant as
If MyFavoriteRestaurantOpen = True Then
Msgbox "Go To My Favorite Restaurant!"
Else
Msgbox "Go Home and Cook!"
End If
This is certainly much simpler to understand, and it's equally helpful when writing
your programs.
VBScript Basics
Page 24 of 52
Chapter 03
Page 25
A few comments are in order about this conditional structure. Notice that only one
of the conditions can be true. If you want to execute code for more than one of
these conditions, you cannot use this control structure. In other words, this
structure can only execute one of the conditions. Once it finds the first condition in
the list that is true, it executes the code off that branch and ignores all the rest.
This would work fine as long as either all the variables are true or False. What if
the user didn't specify which one and both variables were set to False? In that
case, neither would get executed and the user wouldn't see anything. You have to
be careful how you use these structures. If the logic of your problems demands
that at least some action take place for a given condition, either make sure one of
the two variables is set to true before you perform these tests, or be sure to
provide an Else conditional at the end. The Else at the end will executed if none of
the other conditions is true. The Else condition acts as a fallback position just in
case none of the other conditions is True. This might be valuable to you in cases
where you want to make sure something happens in the conditional structure.
After all, when you write code, it's best to take all possibilities into consideration;
you never know when a pesky bug might enter or some unforeseen condition
might take place, and you wouldn't want it to mess up your code.
If condition1 = True Then
...the code that executes for condition1
ElseIf condition2 = True Then
...the code that executes for condition2
ElseIf condition3 = True Then
...the code that executes for condition3
Else
...none condition match
End If
You can add as many ElseIf clauses as you need to provide alternative choices.
Extensive use of the ElseIf clauses often becomes cumbersome. A better way to
choose between several alternatives is the Select Case statement.
The following example shows a simple sampling of the IfThenElse control
structure. Here, you get a variable that shows a user age, just like the first
example. Only this time, rather than perform one check, this code tests a variety
of conditions and responds differently to each one.
If nAge = 0 Then
MsgBox "Welcome to the human race!"
ElseIf nAge < 0 Then
MsgBox "You have to grow up a bit before you start using VBScript!"
ElseIf nAge > 0 And Age < 10 Then
MsgBox "If you're bold enough, you must be old enough."
ElseIf nAge > 120 Then
MsgBox "You're getting too old for this stuff!"
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 25 of 52
Chapter 03
Page 26
Else
MsgBox "You're at the perfect age to get started!"
End If
In this case, you see that you can do more specific checks for various age groups
and even provide an Else clause for the default case. You couldn't do that using
IfThen statements unless you want to write a lot of excess code.
Select Case
Arguments
Argument
Description
testexpression
epressionlist-n
satements-n
elsestatements
Notes
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 26 of 52
Chapter 03
Page 27
Any number of Case clauses can be included in the Select Case statement.
If a match between testexpression and any part of expressionlist is found,
the program statements following the matched expressionlist are executed.
When program execution encounters the next Case clause or the End
Select clause, execution continues with the statement immediately
following the End Select clause.
Both expressionlist and testexpression must be a valid expression that can
consist of one or more of the following: a literal value, a variable, an
arithmetic or comparison operator, or the value returned by an intrinsic or
user-defined function.
If used, the Case Else clause must be the last Case clause. Program
execution encounters the Case Else clause, and thereby executes, the
elsestatementsonly if all other expressionlist comparisons fail.
Select Case statements can also be nested, resulting in a successful match
between testexpression and expressionlist being another Select Case
statement.
Tips
The Select Case statement is the VBA/VBScript equivalent of the Switch
construct found in C and C++.
The Case Else clause is optional. However, as with If...Then...Else
statements, it's often good practice to provide a Case Else to catch the
exceptional instance when, perhaps unexpectedly, a match can't be found in
any of the expressionlists you have provided.
If testexpression satisfies more than one expressionlist comparison, only the
code in the first is executed.
A Select Case structure works with a single testexpression that is
evaluated once, at the top of the structure. The result of the testexpression
is then compared with the values for each Case in the structure.
The Select Case structure provides an alternative to If...Then...ElseIf for
selectively executing one block of statements from among multiple blocks of
statements.
A Select Case statement provides capability similar to the If...Then...Else
statement, but it makes code more efficient and readable. Select Case
structure is defined as follows:
Select Case expression
Case exp-1
...this is the code
Case exp-2, exp-3
...this is the code
Case exp-4
...this is the code
.
.
.
Case Else
...this is the code
End Select
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 27 of 52
Chapter 03
Page 28
Example
The following example uses Select Case to read a variable populated by the
user and determine the name of the user's operating system:
Select Case Left(Environment.Value("OSVersion"), 1)
Case 1 :
varOSDesc = "Windows NT"
Case 2 :
varOSDesc = "Windows 98"
Case 3 :
varOSDesc = "Windows 95"
Case 4 :
varOSDesc = "Windows 3.11"
Case 5 :
varOSDesc = "Windows 2000"
Case 6 :
varOSDesc = "Windows ME"
Case 7 :
varOSDesc = "Windows XP"
Case Else : varOSDesc = "OS is unknown"
End Select
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 28 of 52
Chapter 03
Page 29
Arguments
Argument
Description
counter
start
end
step
Amount counter is changed each time through the loop. If not specified,
step defaults to one.
statements
One or more statements between For and Next that are executed the
specified number of times.
Notes
If start is greater than end, and no step keyword is used or the stepcounter
counter is positive, the For...Next loop is ignored and execution
commences with the first line of code immediately following the Next
statement.
If start and end are equal and stepcounter is one, the loop executes once.
counter can't be a variable of type Boolean or an array element.
counter is incremented by one with each iteration unless the Step keyword
is used.
If the Step keyword is used, step specifies the amount stepcounter is
incremented if stepcounter is positive or decremented if it's negative.
If the Step keyword is used, and stepcounter is negative, start should be
greater than end. If this isn't the case, the loop doesn't execute.
The For...Next loop can contain any number of Exit For statements. When
the Exit For statement is executed, program execution commences with
the first line of code immediately following the Next statement.
For Each subObject In myObj
sName = subObject.NameProperty
If Len(Sname) < 10 Then
Exit For
End if
Next
Tips
The following example causes a procedure called MyProc to execute 50 times.
The For statement specifies the counter variable x and its start and end values.
The Next statement increments the counter variable by 1 as default.
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 29 of 52
Chapter 03
Page 30
For x = 1 To 50
MyProc
Next
Using the Step keyword, you can increase or decrease the counter variable by
the value you specify. In the following example, the counter variable j is
incremented by 2 each time the loop repeats. When the loop is finished, the
total is the sum of 2, 4, 6, 8, and 10.
Dim j, total
For j = 1 To 10 Step 2
total = total + j
Next
MsgBox "The total is " & total
To decrease the counter variable, use a negative Step value. You must specify
an end value that is less than the start value. In the following example, the
counter variable myNum is decreased by 2 each time the loop repeats. When
the loop is finished, total is the sum of 16, 14, 12, 10, 8, 6, 4, and 2.
Dim j, total
For j = 16 To 2 Step -2
total = total + j
Next
MsgBox "The total is " & total
You can exit any For...Next statement before the counter reaches its end value
by using the Exit For statement. Because you usually want to exit only in
certain situations, such as when an error occurs, you should use the Exit For
statement in the True statement block of an If...Then...Else statement. If the
condition is False, the loop runs as usual.
ForNext loops can also be nested.
For nDay = 1 To 365
For nHour = 1 To 23
For nMinute = 1 To 59
. . .
Next
Next
Next
When you use a positive step value, make sure the finish value is greater
than the start value, or the loop will not execute at all.
For i = 10 to 1 Step 2
For i = 1 to 10 Step 2
' Incorrect
' Correct
When you use a negative step value, make sure the start value is greater
than the finish value, or the loop won't execute at all.
For i = 1 to 10 Step -1
For i = 10 to 1 Step -1
' Incorrect
' Correct
Never use a step value of zero. In this case, VBScript will enter an infinite
loop, and your program might run indefinitely.
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 30 of 52
Chapter 03
For i = 1 to 10 Step 0
For i = 1 to 10 Step 3
Page 31
' Incorrect
' Correct
Arguments
Argument
Description
element
group
statements
Notes
The For...Each code block is executed only if group contains at least one
element.
All statements are executed for each element in group in turn until either
there are no more elements in group, or the loop is exited prematurely
using the Exit For statement. Program execution then continues with the
line of code following Next.
For Each...Next loops can be nested, but each element must be unique.
For example:
For Each myObj In anObject
For Each subObject In myObject
sName(ctr) = subObject.NameProperty
ctr = ctr + 1
Next
Next
Uses a nested For Each...Next loop, but two different variables, myObj and
subObject, represent element.
Any number of Exit For statements can be placed with the For
Each...Next loop to allow for conditional exit of the loop prematurely.
On exiting the loop, execution of the program continues with the line
immediately following the Next statement.
For example, the following loop terminates once the program finds a name
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 31 of 52
Chapter 03
Page 32
Tips
Each time the loop executes when iterating the objects in a collection, an
implicit Set statement is executed. The following code reflects the
"longhand" method that is useful for explaining what is actually happening
during each iteration of the For Each...Next loop:
For i = 1 to MyObject.Count
Set myObjVar = MyObject.Item(i)
MsgBox myObjVar.Name
Next
For example, on the first iteration of the loop, although varName has been
changed from "Paul" to "Changed," the underlying array element,
strNameArray(0), still reports a value of "Paul."
This proves that a referential link between the underlying array and object
variable isn't present; instead, the value of the array element is passed to
element by value.
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 32 of 52
Chapter 03
Page 33
Arguments
Argument
Description
condition
statements
Notes
On its own, Do...Loop repeatedly executes the code that is contained
within its boundaries indefinitely. You therefore need to specify under what
conditions the loop is to stop repeating. Sometimes, this requires modifying
the variable that controls loop execution within the loop. For example:
Do
nCtr = nCtr + 1
' Modify loop control variable
MsgBox "Iteration " & nCtr & " of the Do loop..." & vbCrLf
' Compare to upper limit
If nCtr = 10 Then Exit Do
Loop
If condition is True before your code gets to the Do statement, the code
within the Do...Loop is ignored.
Adding the While keyword after Do repeats the code while a particular
condition is True. When the condition becomes False, the loop is
automatically exited. The syntax of the Do While statement is:
Do While condition
code to execute
Loop
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 33 of 52
Chapter 03
Page 34
Arguments
Argument
Description
condition
statements
One or more statements between For and Next that are executed the
specified number of times.
Notes
A Null condition evaluated as False.
If condition evaluates to True, the program code between the While and
Wend statements executed. After the Wend statement is executed, control
is passed back up to the While statement, where condition is evaluated
again. When condition evaluates to False, program execution skips to the
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 34 of 52
Chapter 03
Page 35
VBScript Basics
Page 35 of 52
Chapter 03
Page 36
Sub Procedures
A Sub procedure is a series of VBScript statements (enclosed by Sub and End
Sub statements) that perform actions but don't return a value. A Sub procedure
can take arguments (constants, variables, or expressions that are passed by a
calling procedure). If a Sub procedure has no arguments, its Sub statement must
include an empty set of parentheses ().
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 36 of 52
Chapter 03
Page 37
Function Procedures
A Function procedure is a series of VBScript statements enclosed by the
Function and End Function statements. A Function procedure is similar to a
Sub procedure, but can also return a value. A Function procedure can take
arguments (constants, variables, or expressions that are passed to it by a calling
procedure). If a Function procedure has no arguments, its Function statement
must include an empty set of parentheses. A Function returns a value by
assigning a value to its name in one or more statements of the procedure. The
return type of a Function is always a Variant.
Declaring Subroutines/Functions
There are several very straightforward rules to remember when giving names to
your subroutines/functions:
The name can contain any alphabetical or numeric characters and the
underscore character.
The name cannot start with a numeric character.
The name cannot contain any spaces. Use the underscore character to
separate words to make them easier to read.
For example:
Sub 123MySub( )
Function My Func( )
' Illegal
' Illegal
' Legal
' Legal
VBScript Basics
Page 37 of 52
Chapter 03
Page 38
Calling a Subroutine
Now that you've learned how to create a subroutine, how do you call one? You can
call a subroutine throughout the rest of the application once you've declared and
created it. You can call subroutines by using the Call keyword or just entering the
name of the subroutine on a line of code. For example, to call a subroutine called
ShowMessage, you could enter
ShowMessage "This is the message."
Notice that in the first method, you do not place parentheses around the
arguments of the subroutine. On the other hand, if you use Call, you must enclose
the arguments in parentheses. This is simply a convention that VBScript requires.
What if a subroutine has no arguments? To call the subroutine
ShowAboutMessage, you could enter
ShowAboutMessage
Or
Call ShowAboutMessage()
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 38 of 52
Chapter 03
Page 39
The first method simply lists the name of the subroutine. The second method uses
Call but doesn't require parentheses because the subroutine has no arguments.
Whether you use the parentheses when you call or declare a subroutine with no
arguments is a personal preference about writing code. When you call a subroutine
without the Call statement, it can be more difficult to figure out the difference
between a subroutine and a variable in your code, especially if your code is
lengthy. Although the choice is up to you, it is generally recommended that you
always use the Call statement when calling subroutines for the sake of readability.
Call Statement
Description
The Call statement passes program control to an explicitly named procedure or
function.
Syntax
[Call] procedurename [argumentlist]
Arguments
Parameter
Description
Call
argumentlist
Notes
The Call statement requires that the procedure being called be named
explicitly.
You cannot assign the subroutine name to a variable and provide that as an
argument to the Call statement. For example, the following is an illegal use
of Call:
Dim sProc
sProc = "PrintRoutine"
Call sProc(sReport)
The following code fragment shows a valid use of the Call statement:
Call PrintRoutine(sReport)
You aren't required to use the Call keyword when calling a function
procedure. However, if you use the Call keyword to call a procedure that
requires arguments, argumentlist must be enclosed in parentheses. If you
omit the Call keyword from the procedure call, you must also omit the
parentheses around argumentlist.
Tips
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 39 of 52
Chapter 03
Page 40
You can use the Call keyword to call a function when you're not interested
in the function's return value.
The use of the Call keyword is considered outdated. We suggest not using
the keyword, as it is unnecessary and provides no value.
If you remove the Call statement but fail to remove the parentheses from a
call to a subroutine with a single argument, then that argument is passed
by value rather than by reference. This can have unintended consequences.
Calling a Function
Now that you've seen how to declare a function, you need to know how to call it.
The benefit of using a function is that you can pass back a piece of data to the
caller. The subroutine does not enable you to do this because it does not return
anything. You will see a way to change variables in the calling code with a
subroutine later today, but the function is a better way to get data back and forth.
To call a function, you simply use the syntax
return_variable = function_name(argument1, argument2, , argumentn)
Notice that in this case, the syntax is quite a bit different from the subroutine.
Here, you can assign the function to a variable (or another expression that can be
updated with a value, such as a property, which will be covered in later lessons),
or you needn't assign it to anything. The parentheses are optional only when no
arguments are passed to the function.
For an example of its use, suppose you have a function called GetAge. To use the
GetAge function, you could enter the statement
UserAge = GetAge()
Notice that this function doesn't need any arguments, and the result is assigned to
a variable named UserAge. The following function requires three arguments-hours,
minutes, and seconds-and returns the number of seconds:
Function GetSeconds(Hrs, Min, Sec)
GetSeconds = Hrs * 3600 + Min * 60 + Sec
End Function
Would also be valid, but it wouldn't be very useful because you're not retrieving
the number of seconds from the function! This simply calls a function as if it were
a subroutine, without handling the return value. You can also utilize a function
within an expression, such as
MsgBox "There are " & GetSeconds(2,34,25) & " seconds."
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 40 of 52
Chapter 03
Page 41
You don't need to assign a variable to the return of the function because the return
value is automatically used within the statement. Although this is certainly legal, it
is not always the best programming practice. If you want to use the result of the
function more than once, you must store the result in a variable. Otherwise, you
will have to call the function again and waste the computer's resources in doing
the calculation all over again. Likewise, storing the value in a variable to avoid
repeated calls makes the code more readable and maintainable.
Exiting a Subroutine/Function
The code within your subroutine/function will execute until one of two things
happens. First, the subroutine/function might get down to the last line, the End
Sub/End Function line, which terminates the subroutine and passes the baton
back to the caller. This statement can appear only once at the end of the
subroutine declaration. The second possibility is that VBScript could execute the
following code statement:
Exit Sub (for subroutine)
Exit Function (for functions)
When, placed inside the subroutine/function. You might use this statement if you
need to provide more than one exit point for the subroutine/function. However,
you shouldn't need to use this very often if your subroutine is constructed
properly. Consider the following function:
Public Function ConvertFeetToInches(ByVal nFeet)
If nFeet < 0 Then
Exit Function
Else
ConvertFeetToInches = nFeet * 12
End If
End Function
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 41 of 52
Chapter 03
Page 42
VBScript default is to pass arguments by reference. You can include the ByRef
keyword in an argument list if desired but, because this is the default, it has no
effect:
Sub Foo(ByRef Arg1, ByRef Arg2)
The procedure is passed the address of the argument variable (in other words, a
reference to the variable):
Dim Total
Call MySub(Total)
After this code executes, the variable Total equals 50 because the code in the
procedure changed its value. To pass an argument by value, use the ByVal
keyword
Sub MySub(ByVal Total)
When you use ByVal, the procedure is passed a copy of the argument variable
and not a reference to the argument variable itself. Code in the procedure cannot
change the variable's value.
Sub MySub(ByVal Total)
Total = 50
End Sub
VBScript Basics
Page 42 of 52
Chapter 03
Page 43
in the first place. There are three primary reasons: readability, maintainability, and
correctness
Procedures are useful any time you have a task that must be accomplished many
times, perhaps in many places in your code, throughout your program. Suppose
you request an order number from the user, and each time the number is entered,
you want to make sure it's valid. One option is to write code that checks each time
an order is entered. The following code should be placed in a function.
SpouseOrder = InputBox("What order would you like for your spouse?")
If SpouseOrder < 0 Then
MsgBox "The order number is invalid."
End If
YourOrder = InputBox("What order would you like for yourself?")
If YourOrder < 0 Then
MsgBox "The order number is invalid."
End If
ChildOrder = InputBox("What order would you like for your children?")
If ChildOrder < 0 Then
MsgBox "The order number is invalid."
End If
As you can see from this example, the same check is repeated three times in your
code, this results in code that is not only more difficult to read, but also more
difficult to maintain.
Rather than type the same code three times, wouldn't it make your code more
readable if you created a function and placed the repeating code within that
function? Suppose you call the function VerifyOrderNumber and place the common
code in that function.
Public Function VerifyOrderNumber(ByVal nOrderNumber)
' initializing return value
VerifyOrderNumber = False
If IsNumeric(nOrderNumber) = False Then
MsgBox "Not s number."
Exit Function
ElseIf nOrderNumber < 0 Then
MsgBox "The order number is invalid."
Else
VerifyOrderNumber = True
End If
End Function
VBScript Basics
Page 43 of 52
Chapter 03
Page 44
If the user enters values greater than zero, the function returns with a Boolean
variable indicating the result is valid. Otherwise, the function returns the Boolean
value for false, and the loop continues to prompt the user until an order number
entered, calling the function again each time through.
In this case, you have placed all the repeating code within a function so that the
code within the function appears just once rather than several times throughout
the program. Doing this has several advantages. First of all, it's a lot easier for the
reader of the code. He can see what the code does in one word rather than having
to wade through all the details. Furthermore, it cuts down on the size of the code
listing. Perhaps most important, it makes the code more maintainable.
Exit Statement
Description
The Exit statement exits a block of Do...Loop, For...Next, Function, or Sub
code.
Syntax
Exit Do
Exit For
Exit Function
Exit Property
Exit Sub
The Exit statement syntax has these forms:
Statement
Description
Exit Do
Exit For
Exit Function
Exit Sub
Exit Property
Tips
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 44 of 52
Chapter 03
Page 45
Traditional programming theory recommends one entry point and one exit point
for each procedure. However, you can improve the readability of long routines
by using the Exit statement. Using Exit Sub can save having to wrap almost an
entire subroutine (which could be tens of lines long) within an If...Then
statement.
With Exit Sub:
Sub MyTestSub(nNumber)
If nNumber = 10 Then
Exit Sub
End If
...'code
End Sub
In the case of the Exit Function, Exit Property, and Exit Sub statements, the
point in the program to which program flow returns depends on the caller of the
Property, Function, or Sub, respectively, and not on the Property,
Function, or Sub itself.
Coding Conventions
Coding conventions are suggestions that may help you write code using Microsoft
Visual Basic Scripting Edition. Coding conventions can include the following:
Naming conventions for objects, variables, and procedures
Commenting conventions
Text formatting and indenting guidelines
The main reason for using a consistent set of coding conventions is to standardize
the structure and coding style of a script or set of scripts so that you and others
can easily read and understand the code.
Using good coding conventions results in precise, readable, and unambiguous
source. code that is consistent with other language conventions and as intuitive as
possible.
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 45 of 52
Chapter 03
Page 46
Prefix
Example
Boolean
bExist
DateTime
dNow
String
sName
Object
oFile
n (numeric)
nCounter
Single, Double
fPrice
Error
err
errResponse
Array
arr
arrLabels
Currency
cDollar
prefix
ADODB.Connection
oConn
ADODB.Recordset
oRst
Scipting.FileSystemObject
oFso
Scipting.TextStream
oTxt
Scripting.Dictionary
oDic
Shell.Application
oWsh
Excel.Application
oXls
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 46 of 52
Chapter 03
Page 47
: <Action name>
: <Propose>
'@Author
: <Author Name>
'@CreationDate : <dd-mmm-yyyy>
'@inParameter
'@inParameter
'@DtParam
'@DtParam
: <Additional information>
'
'TEST HEADER
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Option Explicit
'--- Constant Declarations
'declare here your constants
'--- Variable Declarations
'declare here your variables
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 47 of 52
Chapter 03
Page 48
Here I want to show how documentation of functions can enhance the QuickTest
auto documentation feature the keyword view. The Keyword View can contain any
of the following columns: Item, Operation, Value, Assignment, Comment, and
Documentation. Where the Documentation column is a Read-only autodocumentation of what the step does, in an easy-to-understand sentence.
For Example, I have this a simple Sum function on an external vbs file.
Function Sum(ByVal a, ByVal b)
Sum = a+ b
End Function
: <Your Description>
: <module name>
'@Author
'@Date
'@InParameter
: <dd-mmm-yyyy>
: <<[in/out]> Name, <type>, <description>
'@ReturnValue
'@Modification
'@ReturnValue
'
'@Remarks
: <additional info>
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 48 of 52
Chapter 03
Page 49
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 49 of 52
Chapter 03
Page 50
General
Code Indentation
Code Indentation is, almost as important as writing code itself.
Code blocks are defined by their indentation. By "code block", I mean functions, if
statements, for loops, while loops, and so forth. Indenting starts a block and
unindenting ends it. There are no explicit braces, brackets, or keywords. This
means that whitespace is significant, and must be consistent.
Indent standard nested blocks four spaces.
Indent the overview comments of a procedure one space.
Indent the highest level statements that follow the overview comments four
spaces, with each nested block indented an additional four spaces.
The following code adheres to VBScript coding conventions.
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 50 of 52
Chapter 03
Page 51
:
<Name>, <Type>, <Description>
'***********************************************************************
QTP User's Guide > Creating Tests or Components > Working with Actions > Creating an Action
Template
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 51 of 52
Chapter 03
Page 52
Dani Vainstein
daniva1968@hotmail.com
VBScript Basics
Page 52 of 52