Showing posts with label vb scripting. Show all posts
Showing posts with label vb scripting. Show all posts

Wednesday, April 14, 2010

VB Scripting - Looping Constructs

Previous11121314151617181920Next

Different types of Looping Constructs in VB Script and its usage in VB Scripting.


Looping constructs allows a user to run a group of statements or piece of code repeatedly that many times as desired by the user. There are some loops which repeat statements until the condition become false and others loops which repeat statements until the condition becomes true. Also there are those loops which repeat statements for a specific number of times.

There are different kinds of looping construct and based on the requirements we can use any of this Looping constructs. The are basically two types of looping constructs FOR and DO. Let’s look at them

FOR Looping Construct

1. For Next Loop
2. For Step Next Loop
3. For Each Next


DO looping Constructs

1. Do Loop While
2. Do Loop Until
3. Do While Loop
4. Do Until Loop
5. While WEnd Loop


Previous11121314151617181920Next

VB Scripting - Constants - Built In Constants

Previous11121314151617181920Next


What is a Built in Constant in VB script?

Built in Constants are those which are already created and stored in VB Library and they cannot be changed and they can be used as it is for various purposes. They in turn help you to print information with meaning and also messages with some action.



Different types of Built in Constants

Please find the list of built in constant and their meaning.

Built in ConstantsWhat it does
vbOKOnlyOK button only
vbOKCancelOK and Cancel buttons
vbAbortRetryIgnoreAbort, Retry, and Ignore buttons
vbYesNoCancel Yes, No, and Cancel buttons
vbYesNoYes and No buttons
vbRetryCancel Retry and Cancel buttons
vbCritical Critical Message icon
vbQuestion Warning Query icon
vbExclamation Warning Message icon
vbInformation Information Message icon
vbDefaultButton1 First button is default
vbDefaultButton2 Second button is default
vbDefaultButton3 Third button is default
vbDefaultButton4 Fourth button is default
vbApplicationModal Application modal i.e. the current application will not work until the user responds to the message box
vbSystemModal System modal i.e. all applications wont work until the user responds to the message box


Example

Const TEST = "Are you sure you want to exit"
msgbox TEST, vbYesNo

The message box displayed will be like this with Yes and No buttons.



Previous11121314151617181920Next

VB Scripting - Constants

Previous11121314151617181920Next

Constant in VB Scripting is a meaningful and specific name that takes the place of a data type like integer or string and never changes. There are two types of constants.



1. Named Constant
2. Built in Constant

Constant is like a variable but unlike variable the value does not change for the constant. It is a permanent value stored in the memory.

Named Constant

You will actually assign a integer or a string to a variable but the value assigned to this variable cannot be changed. It is like a variable but not behave like a variable. The value does not change and it cannot be used as a variable.

As part of the coding convention it is better to write all the constants in upper case even though VB Scripting is case insensitive but for easy understanding it is written and this makes no difference.

Note: The variables are written in lower case. A constant cannot be used as a variable.

You can create user defined constants using the const statement and can be created on numeric and string values giving meaningful names.

Syntax

Const [Name] = [Expression]


Const GREETING = “Welcome to the world of constants”
Const Age = 50


Example

Const GREETING = “Welcome to VB Scripting”
Msgbox GREETING


Previous11121314151617181920Next

Tuesday, April 13, 2010

VB Scripting - Select Case

Previous11121314151617181920Next

Select Case statement in VB Scripting is also a branching statement. We branch out the code by evaluating one expression. Select Case is an alternative for If Else. Select Case can be used invariably (any where)



Syntax for Select Case Statement


Select Case [condition]
Case 1
aaaCode
Case 2
aaaCode
Case 3
aaaCode
Case Else
aaaCode
End Select


Example to understand it easily


Let us write a script which can display the resultant value of two integers based on the selection made. We are computing Addition, Subtraction, Multiplication and division of the two integers and based on the user selection the operation is performed.

UserInput = Inputbox("Enter any of the following options"&vbnewline&" " &vbnewline&"1 for Addition"&vbnewline&"2 for Subtraction"&vbnewline&"3 for Multiplication"&vbnewline&"4 for Division")

Var1 = CINT(Inputbox("Enter the First Value"))
Var2 = CINT(Inputbox("Enter the Second Value"))

Select Case UserInput

Case 1
aaamsgbox"The Sumation of "&Var1& " and " &var2& " is: "&Var1 + Var2
Case 2
aaamsgbox"The difference between "&Var1& " and " &var2& " is: "&Var1 - Var2
Case 3
aaamsgbox"The product of "&Var1& " and " &var2& " is: "&Var1 * Var2
Case 4
aaamsgbox"The quotient between "&Var1& " and " &var2& " is: "&Var1 \ Var2
Case Else
aaamsgbox "Invalid entry"
End Select


Previous11121314151617181920Next

Answers to Assignments for If Else Statement

Please find the answer to the assignment on If Else statements.

1. Write a script to print the greatest of three integers.


Look at the script below.

Var1 = CINT(Inputbox("Enter value for Var1: "))
Var2 = CINT(Inputbox("Enter value for Var2: "))
Var3 = CINT(Inputbox("Enter value for Var3: "))

if Var1=Var2 and Var1=Var3 then
aaaamsgbox"All the values are same: "&Var1
elseif Var1=Var2 and Var1>Var3 then
aaaamsgbox"Var1 & Var2 i.e. " &Var1& " is greater than "&Var3
elseif Var1=Var3 and Var1>Var2 then
aaaamsgbox"Var1 & Var3 i.e. " &Var1& " is greater than "&Var2
elseif Var2=Var3 and Var2>Var1 then
aaaamsgbox "Var2 & Var3 i.e. " &Var2& " is greater than "&Var1
elseif Var1>Var2 and Var1>Var3 then
aaaamsgbox "Var1 i.e. "&Var1& " is greater than "&Var2& ", "&Var3
elseif Var2>Var1 and Var2>Var3 then
aaaamsgbox "Var2 i.e. "&Var2& " is greater than "&Var1& ", "&Var3
else
aaaamsgbox "Var3 i.e. "&Var3& " is greater than "&Var1& ", "&Var2
end if

In the above script we are joining the values and some meaning ful string to the message and this is done using the '&' which is to join the strings.

2. Write a script to print the least of the three integers.

For this please think and write. you have to only make some small change.

Back to If Else Statement page

VB Scripting - Else If Statement

Previous11121314151617181920Next


The If Else statement we discussed previously executes one block of code if the value is greater than 80 or executes the other piece of code if the condition is not satisfied. Now think what you will do if you have different ranges.

To do this you need Else If statement.



What Else if does is that it creates and if statement within an if statement and goes on and in this manner you can check different conditions in a single if Statement.

Syntax for Else If Statement



If [condition] Then
Code
Elseif [condition] Then
Code
Elseif [condition] Then
Code
Elseif [condition] Then
Code
Else
Code
End If


Example to show how Else If Statement is used


Now let write a script to see how this works. We will calculate the average for three subjects and based on the percentage we will display the average and the appropriate messages.


'Calculating the average for three subjects
mt = Inputbox("Enter the marks scored for Manual Testing:")
qtp = Inputbox("Enter the marks scored for QTP:")
sql = Inputbox("Enter the marks scored for SQL:")
'Calculating average
avg=(mt+qtp+sql)/3
'Displaying the average to the user
msgbox "The average marks scored is: "&avg
'Branching statements to display appropriate message
If avg >= 90 Then
msgbox "You scored "&avg&" percentage and you will get a Job"
ElseIf avg >= 80 and avg < 90 Then
msgbox "You scored "&avg&" percentage and you have to put in more effort"
ElseIf avg >= 70 and avg < 80 Then
msgbox "You scored "&avg&" percentage and you are not up to the mark"
Else
msgbox "You scored "&avg&" percentage and you have to repeat the course"
End If



What happened why did this result came as 100.333333333333 and the first message will be displayed which is wrong.

Let’s debug the script line by line.

mt=3, qtp=0, sql=1
avg=(mt+qtp+sql)/3
avg=(3+0+1)/3
avg 301/3
avg=100.333333333333


Let me explain you what happened so that we will be clear as to what happened and how to rectify the code.

Even though we say that in the condition avg=(mt+qtp+sql)/3 we have used addition (+) operator but just to remind that the default type of Inputbox is string because we have not explicitly declared the variables and that’s why by default what ever values you have entered in the input box is taken as string and in context of this + is treated as a concatenation operator which means that it will join the three values as 3+0+1 to make 301 and not add them up to 4. That is the reason we are getting a different result.

In order to rectify this issue we need to use a conversion type (Type Cast) which in our case actually converts the default data type to integer type. For this we need to use CINT. CINT can be used with input box or while on the expression calculating the average (In our case). You cannot use CINT for some variables while accepting values and for some on the expression. You can either use CINT on the expression or while taking input on variables.


Let’s rewrite the code and see what happens

'Calculating the average for three subjects
mt = CINT(Inputbox("Enter the marks scored for Manual Testing:"))
qtp = CINT(Inputbox("Enter the marks scored for QTP:"))
sql = CINT(Inputbox("Enter the marks scored for SQL:"))
'Calculating average
avg=(mt+qtp+sql)/3
'Displaying the average to the user
msgbox "The average marks scored is: "&avg
'Branching statements to display appropriate message
If avg >= 90 Then
msgbox "You scored "&avg&" percentage and you will get a Job"
ElseIf avg >= 80 and avg < 90 Then
msgbox "You scored "&avg&" percentage and you have to put in more effort"
ElseIf avg >= 70 and avg < 80 Then
msgbox "You scored "&avg&" percentage and you are not up to the mark"
Else
msgbox "You scored "&avg&" percentage and you have to repeat the course"
End If




Now run the script and you will get the right percentage and the required message.

Note: You can also use CINT on the expression instead on inputbox. It will look like this.
(CINT(mt)+CINT(qtp)+CINT(sql))\3

Assignments on Else If Statement

1. Write a script to print the greatest of three integers.
2. Write a script to print the least of the three integers.

Click Here for answers for Assignments


Previous11121314151617181920Next

VB Scripting - If Statement

Previous11121314151617181920Next


If Else statement in VB script is used when you want to execute a block of code based on certain condition.


Syntax for If Else Statement


If [Condition] Then
AAAACode
AAAACode
Else
AAAACode
AAAACode
End If


Example to show how If Else Statement is Used


We will write a script asking the user to enter the average scored and based conditions given appropriate message is displayed.

'Code to demonstrate If Else condition
Varint1 = Inputbox("Enter the average score you gained:")
If Varint1 > 80 Then
AAAAmsgbox "You scored " &Varint1& " percentage and are the winner"
Else
AAAAmsgbox "You scored " &Varint1& " percentage and do not qualify."
End If


If the user enters 85 then the output displayed will be

You Scored 85 percentage and are the winner


If user enters any thing less than 80 say 75 the output displayed will be

You Scored 85 percentage and do not qualify.


Previous11121314151617181920Next

VB Scripting - Branching Statements

Previous11121314151617181920Next

What is Branching and types of Branching Statements?


Branching Statements in VB Scripting provides a user with a choice to execute certain piece of code based on the condition. This would help us to validate different conditions for one expression.


In general to say that the program or code has to make a decision based on a condition when a user gives a input or based on some parameters or values the decision has to be made then branching statements plays a vital role.

For example take this scenario of giving different grades to a student based on the percentage. For one student you can assign the marks to different variables and based on the average you can branch out your code and give the grade but imagine if you have to run it for more that one student then manually you have to go into the code and change for every student and save and run.

Branching Statements helps you in making the code decide the grade based on the conditions you give in the code once and ask the user to enter the marks for each student. Using these branching statements you can branch out your code to different conditions.

Basically there are three types of Branching Statements

1. If Else
2. If Elseif
3. Switch Case


Out of these the popular branching or conditional statement used is the If Else, Endif

Else and Elseif are used to branch out different conditions.

Previous11121314151617181920Next

Monday, April 12, 2010

VB Scripting - Operators

Previous12345678910Next

What is the need for Operators?


Operators in VB Script are to used to perform some operations or do some manipulation on variables or values. Operator is a notation to perform operation and this operation will happen on one or more operands.


Operators in VB script can be classified in to mainly four. They are

  • Arithmetic Operators.
  • Logical Operators.
  • Relational or Comparison Operators.
  • Concatenation Operator.

  • VB Script – Arithmetic Operators


    Arithmetic operators are used for arithmetic operations or mathematical operations such as Addition, Subtraction, Multiplication and other kinds of operations.
    Please find the list of Operators with some examples for easy understanding.

    Operator English MeaningExample Result
    + Add 5+27
    - Subtract 5-23
    * Multiply 5*210
    / Floating Point Division 5/22.5
    \Integer Division5\22
    ^ Exponent 5^225
    Mod Modulus 5 Mod 2 1

    Logical Operators


    Logical operators are used to perform logical operations. They are used to manipulate statements or create logical expressions. The Logical operators are AND, OR and NOT.
    Please find the list of Operators with some examples for easy understanding.

    Operator English MeaningExample Result
    Not Inverts Value Not False True
    Or Either Can Be True True or False True
    And Both Must Be True True And False False

    Relational or Comparison Operators


    Relational operators are also called as comparative operators like if we want to compare numbers etc. Generally they are used in conditional statements like IF Else or While loops.
    Please find the list of Operators with some examples for easy understanding.

    Operator English MeaningExample Result
    = Equal To 20 = 45False
    > Greater Than 20 > 45 False
    < Less Than 20 <>True
    >= Greater Than or Equal To 20 >= 45False
    <= Less Than or Equal To 20 <= 45 True
    <>Not Equal To 20 <> 45 True

    Concatenation Operator


    In order to combine two strings and display as a single string we use Concatenation Operator (&). We use “&” to join two expressions.
    Please find below the description with examples for easy understanding.

    Operator English MeaningExample Result
    &Join or Connect"Hello" & "World"Hello World


    Previous12345678910Next

VB Scripting - Data Types

Previous12345678910Next

What are the Data Types in VB Script?


Data types in VB Script is used in context of Variable. There is only one data type in VB Script called as Variant. The specialty of a Variant is that it can hold different forms of data or information within the variable and there is no need to explicitly define the type of data.


A Variant can hold data which contains either a numeric or a string value. The Variant behaves in the way you want i.e. behaves as a numeric value when used in a numeric context and behaves like a string when used in a string context. The only difference is that any data which is enclosed in quotation marks (" ") behaves like a string even though it contains only numbers.

Variant Subtypes


Variant can hold any type of data like Integer, String, Long, Single or double etc. The different categories of information/data which a Variant can hold are called as subtypes.

Below table gives a clear picture of subtypes of data which a Variant can hold or contain.
SubtypeDescription
IntegerThe size is of 2 bytes, Value can be from 0 to 255, The Integer range is from -32,768 to 32,767.
Long Long is for numbering system, The Integer range is from -2,147,483,648 to 2,147,483,647.
SingleHolds small precision, floating point range is from -3.402823E38 to -1.401298E-45 for negative values and for positive values is from 1.401298E-45 to 3.402823E38.
DoubleHolds big precision, floating point range is from -1.79769313486232E308 to -4.94065645841247E-324 for negative values and for positive values is from 4.94065645841247E-324 to 1.79769313486232E308.
CurrencyRanges from -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Date (Time)The range is between January 1, 100 to December 31, 9999.
ObjectContains an object.
BooleanContains a boolean value either True or False.
EmptyVariant is uninitialized. Value is 0 for numeric variables or a zero-length string ("") for string variables.
NullVariant intentionally contains no valid data.
ByteContains integer in the range 0 to 255.


You can use the conversion functions to convert the data from one subtype to another subtype which will be discussed in Type Cast lesson.

Previous12345678910Next

VB Script - Variable - Explicit Declaration

Previous12345678910Next

Explicit Declaration


Explicit Declaration is used to avoid the unnecessary confusion created while typing and also to avoid loading the memory with variables because of errors we can use Explicit Declaration. In order to use explicit declaration type we need to declare the variables before the script begins or it should be in the starting of the script.


We will use the same example used for Implicit Declaration but will change the script. In order to create Explicit Declaration in the beginning of the code we need to add one more line of code as ‘Option Explicit”. Take a look at the code for Explicit Declaration

Option Explicit
Dim Int1, Int2, Prod
Int1 = 28
Int2 = 30
Prod = Int1 * Int2
Msgbox Prod

Now lets debug the code. If by mistake instead of “Prod” you type “Prd” in Line 6 as Msgbox Prd then what will happen. Since “Prd” is not declared when you run the script it executes the first five line and when it executes the sixth line it throws error and till it is not rectified the resultant output is not displayed. It will throw error as “Variable is undefined: ‘Prd’.

This is the advantage of using Explicit Declaration.

Previous12345678910Next

VB Scripting - Variables - Implicit Declaration

Previous12345678910Next

Implicit Declaration:


Implicit Declaration is a default declaration type in VB and there is no need for us to declare a variable before assigning a value to the variable. The declaration and definition happens in one step.


Implicit declaration is easy to use. We don’t need to keep track of the variables used in the VB script.

Example

Int1 = 28
Int2 = 30
Prod = Int1 * Int2
Msgbox Prod

Let’s see how this is stored in the memory.








From the above example Int1 and Int2 are operands and the * is the operator and = is the assignment operator. Int1, Int2, Prod are Implicit Variables and as the script is executed in the memory the variables get created in the memory and the respective values are stored in those locations. With this type of declaration it is easy to create variables as and when required.

The one disadvantage of Implicit variables is that if there is a typo error in any line like for example "Prod" is mistyped as "Prd" then when the scrip is executed it creates another variable called "Prd" and the resultant out put is null (Nothing will be displayed). We should be careful in using the Implicit Declarations.

Previous12345678910Next

VB Scripting - Variable Declaration


Previous12345678910Next

What is a Variable?

Variable in VB Script is a place holder in the memory used to store some data or information.


The information assigned in the variable is a reserved section in the computer’s memory for storing data. The Memory used is temporary. The information stored in the memory is not permanent.

Rules for VBScript Variable usage


A variable in the VB script cannot start with a numeric value (Ex – 1stvalue). It can be a combination of Alphabets and Numbers together (Value1) or separated by a underscore (Value_1). There is no way you can use arithmetic operators and also space is not allowed because if space is given then VB script will recognize them as two different variables. Below are the basic rules followed while creating a Variable.
  • It must always begin with a letter
  • Should not contain a period (.) or arithmetic operators (+, -, *, /, ^)
  • The max length of the variable is 256 characters

Types of Variable Declaration


In VB Script Variable Declaration happens in two ways:

1. Implicit Declaration.
2. Explicit Declaration.

Assigning values to a Variable


A value to a variable can be assigned either using Implicit Declaration or Explicit Declaration.

Example

Value1=20
Jobtype=“Permanent”

From the above we can see that = is an assignment operator. The left hand side of the expression is the variable name and the right hand side of the expression is the value assigned to the variable.


Previous12345678910Next