[go: up one dir, main page]

0% found this document useful (0 votes)
100 views33 pages

Introduction To VB Script What Is A Variable?

The document provides an introduction to variables in VBScript. It defines a variable as a container that stores program information that can change during script execution. Variables in VBScript are always of the variant data type. The document also discusses variable naming conventions and restrictions, and how to create variables using the Dim statement or by implicit declaration. It describes the Option Explicit statement for forcing explicit variable declaration and provides examples of working with arrays and constants in VBScript.

Uploaded by

Sanjay PN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views33 pages

Introduction To VB Script What Is A Variable?

The document provides an introduction to variables in VBScript. It defines a variable as a container that stores program information that can change during script execution. Variables in VBScript are always of the variant data type. The document also discusses variable naming conventions and restrictions, and how to create variables using the Dim statement or by implicit declaration. It describes the Option Explicit statement for forcing explicit variable declaration and provides examples of working with arrays and constants in VBScript.

Uploaded by

Sanjay PN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 33

INTRODUCTION TO VB SCRIPT

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.

Variables Naming Restrictions


Variable names follow the standard rules for naming anything in
VBScript. A variable name:
Must begin with an alphabetic character.
Cannot contain an embedded period.
Must not exceed 255 characters.
Must be unique in the scope in which it is declared.
Make sure you never create variables that have the same name
as keywords already used by VBScript.

These keywords are called reserved words and include terms


such as Date, Minute, Second, Time, and so on.

How Do I Create a Variable?


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 computer 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 Dim
keyword to tell VBScript you are about to create a variable. You then
follow this keyword with the name of the variable. If, for example,
you want to create a variable called Quantity, you would enter
Dim nQuantity
And the variable will then exist.
Syntax
Dim varname[([subscripts])][, varname[([subscripts])]] . . .

Option Explicit Statement


Forces explicit declaration of all variables in a script.
If used, the Option Explicit statement must appear in a script before
any other statements. When you use the Option Explicit statement,
you must explicitly declare all variables using the Dim, Private,
Public, or ReDim statements. If you attempt to use an undeclared
variable name, an error occurs like in Figure.
Undefined variable error.

Tip
Use Option Explicit to avoid incorrectly typing the name of an existing
variable or to avoid confusion in code where the scope of the variable
is not clear.
The following example illustrates use of the Option Explicit
statement.

Working with Arrays


We know 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 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 array 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 name.
Arrays are useful when you're storing sets of similar data because
they often make it easier to manipulate the data together.

Fixed Length Arrays


In the following example, a single-dimension array
containing 11 elements is declared:
Dim arrArray(10)
Although the number shown in the parentheses is
10, all arrays in VBScript are zero-based, so this
array actually contains 11 elements.
In a zero-based array, the number of array elements
is always the number shown in parentheses plus one.
This kind of array is called a fixed-size array.

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 "redimension the array to however many elements you specify. ReDim takes
dimensions the same way Dim can. The syntax is
ReDim arrName(nCount - 1)

So, if you enter


ReDim arrNames(9)
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.

VBScript Constants
Sometimes in writing code, you will want to refer to values that never
change.
Users can create their own constants by initializing variables
accordingly and then not changing their value.
Using the Const statement, you can create string or numeric
constants with meaningful names and assign them literal values. For
example:

Constant Naming Conventions


Constant names should be uppercase with underscores (_) between
words. For example:

Conditional Statements
Using conditional statements, you can write
VBScript code that makes decisions and
repeats actions
If...Then...Else statement
If value = 0 Then
MsgBox value
ElseIf value = 1 Then
MsgBox value
ElseIf value = 2 then
Msgbox value

Else
Msgbox "Value out of range!"
End If

Looping allows you to run a group of statements repeatedly. Some


loops repeat statements until a condition is False; others repeat
statements until a condition is True. There are also loops that
repeat statements a specific number of times.
The following looping statements are available in VBScript:

Do...Loop: Loops while or until a condition is True.


While...Wend: Loops while a condition is True.
For...Next: Uses a counter to run statements a specified number of
times.

For Each...Next: Repeats a group of statements for each item in a


collection or each element of an array.

VBScript Procedures
Kinds of Procedures
In VBScript there are two kinds of
procedures; the Sub procedure and the
Function procedure.

Sub Procedures
A Sub procedure is a series of VBScript
statements, enclosed by the Sub and End Sub
statements, that performs actions but doesn'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.

Call ConvertTemp() Calling a Sub


Sub ConvertTemp()
temp = InputBox("Please enter the temperature in degrees
F.", 1)
MsgBox "The temperature is " & Celsius(temp) & " degrees
C."
End Sub

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.

Temp= Celsius(fDegrees)Calling a function (in case function returns a value)


Function Celsius(fDegrees)
Celsius = (fDegrees - 32) * 5 / 9
End Function

Call Celsius(fDegrees)Function Call (in case function doesnt returns a value)


Function Celsius(fDegrees)
Temp = (fDegrees - 32) * 5 / 9
Msgbox Temp
End Function

FileSystemObject Basics

Dim fso, MyFile


Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)
MyFile.WriteLine("This is a test.")
MyFile.Close

MsgBox Function
Description
Displays a dialog box containing a message,
buttons, and optional icon to the user.
Syntax
MsgBox(prompt, buttons, title, helpfile, context)

Instr Functions
Description
Returns the position of the first occurrence of one string within
another.
Syntax
InStr (start, string1, string2, compare)
Arguments

Return Value
Variant of type Long.

Notes
The return value of InStr is influenced by the values of string1 (string to
search) and string2 (string to find)
If the start argument is omitted, InStr commences the search with the first
character of string1.
If the start argument is Null, an error occurs.

You must specify a start argument if you are specifying a compare


argument.
VBScript supports intrinsic constants for compare.
In effect, a binary comparison means that the search for string2 in string1
is case-sensitive. A text comparison means that the search for string2 in
string1 is not case-sensitive.
If the compare argument contains Null, an error is generated.
If compare is omitted, the type of comparison is vbBinaryCompare.

Example

LCase, UCase Functions


Description
LCase function converts a string to lowercase.
UCase function converts a string to uppercase.
Syntax

Arguments

Return Value
Variant of type String.

Notes
LCase affects only uppercase letters; all other characters in string are
unaffected.
LCase returns Null if string contains a Null.

UCase affects only lowercase alphabetical letters; all other characters


within string remain unaffected.
UCase returns Null if string contains a Null.
The LCase and UCase functions, helps the QuickTest programmer to
avoid case-sensitive coding when reading data

Left Function
Description
The Left function returns a specified number of characters
from the left side of a string.
Syntax
Arguments

Return Value ? Variant of type String.

Notes
If length is 0, a zero-length string (" ") is returned.
If length is greater than the length of string, string is returned.
If length is less than 0 or Null, the function generates runtime error
If string contains Null, Left returns Null.

Right Function
Description
The Right function returns a specified number of characters from
the right side of a string.
Syntax
Arguments

Return Value?
Notes

Variant of type String.

If length is 0, a zero-length string (" ") is returned.


If length is greater than the length of string, string is returned.
If length is less than 0 or Null, the function generates a runtime error.

If string contains Null, Right returns Null.

Len Function
Description
The Len function returns the number of characters in a string or the
number of bytes required to store a variable.
Syntax
Arguments

Return Value

Variant of type Long.

Notes
string and varname are mutually exclusive; that is, you must specify either
string or varname, but not both.
If either string or varname is Null, Len and LenB return Null.
You can't use Len with an object variable.
If varname is an array, you must also specify a valid subscript. In other
words, Len can't determine the total number of elements in or the total size
of an array.

LTrim, RTrim and Trim Functions


Description
Returns a copy of a string without leading spaces (LTrim), trailing
spaces (RTrim), or both leading and trailing spaces (Trim).
Syntax

Arguments
Return Value

Variant of type String.

Notes
If string contains a Null, LTrim returns Null.
If string contains a Null, RTrim returns Null.
If string contains a Null, Trim returns Null.

UBound Function
Description
The UBound returns the largest available subscript for the indicated
dimension of an array.
Syntax
Arguments

Return Value Variant of type Long.


Notes
If dimension is not specified, 1 is assumed. To determine the
upper limit of the first dimension of an array created by VBScript
code, set dimension to 1, set it to 2 for the second dimension, and
so on.
The upper bound of an array dimension can be set to any integer
value using Dim, Private, Public, and Redim.

LBound Function
Description
The LBound function returns the smallest available subscript for the
indicated dimension of an array.
Syntax
Arguments

Return Value Variant of type Long (0)

Notes
If dimension isn't specified, 1 is assumed. To determine the lower
limit of the first dimension of an array, set dimension to 1, to 2 for
the second, and so on.

Split Function
Description
The Split function returns a zero-based, one-dimensional array
containing a specified number of substrings.
Syntax
Arguments

Return Value
A variant array consisting of the arguments passed into the function.

Notes
If delimiter isn't found in expression, Split returns the entire string
in element 0 of the return array.
If delimiter is omitted, a space character is used as the delimiter.
If count is omitted or its value is -1, all strings are returned.
The default comparison method is vbBinaryCompare. If delimiter is
an alphabetic character, this setting controls whether the search for it
in expression is case-sensitive (vbBinaryCompare) or not
(vbTextCompare).

Array Function
Description
The Array function returns a variant array containing the elements
whose values are passed to the function as arguments.
Syntax

Arguments

Return Value

A variant array consisting of the arguments passed


into the function.

Notes
Although the array you create with the Array function is a variant
array data type, the individual elements of the array can be a mixture
of different data types.
The initial size of the array you create is the number of arguments
you place in the argument list and pass to the Array function.

The lower bound of the array created by the Array function is 0.


The array returned by the Array function is a dynamic rather than a
static array.Once created, you can re-dimension the array using
Redim, Redim Preserve, or another call to the Array function.

You might also like