Showing posts with label Visual Basic Scripting. Show all posts
Showing posts with label Visual Basic Scripting. Show all posts

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

Friday, April 9, 2010

VB Scripting - Building Blocks

Previous12345678910Next

VB Scripting has some building blocks and are important to know them and use them in an appropriate manner. Below are given the building blocks used in VB Scripting.



1. Variable has something called as data types.

2. Operators like =,+,-,* etc..

3. Branching statements to make decisions (If then else conditions)

4. Looping Constructs (For loop, While loop)

5. Functions and Procedures

6. String, Conversion, Date and Time

7. File System Object

Previous12345678910Next

VB Scripting Basics - Input Box Function

Previous12345678910Next

Input box function in VB Scripting is used to get information from the user and then that value is stored in a variable.


Type in the statement below in your note pad and save as sample2.


UserInput = Inputbox(“Please Enter your Name”)


When you execute the file by double clicking it is displayed like this.


“UserInput” in the above statement is a variable and whatever the user enters in the text box is stored in the variable called “UserInput”. If we want to view the data entered on the screen then we need to call this variable in the Msgbox function and the variable value is displayed for the user. In order to do this modify your code like this

UserInput = Inputbox(“Please Enter your Name”)
Msgbox  UserInput


When you execute the file again with this changes what happens. First you are prompted to enter a value and clicking OK button will display the message box with the value entered.

To put in as a definition Input box is an inbuilt VB Scrip function used for getting an input from the user during runtime. Input box provides a text box and allows the user to type in some data. When the user clicks the OK button this data is assigned to a variable. The default input type for an input box is a string.

Previous12345678910Next

VB Scripting Basics - Msgbox Function

Previous12345678910Next

Msgbox Function in VB Scripting is a very basic function and Let’s start with a simple VB Script to display a message for the user using the Msgbox Function and try to understand how it works.


Msgbox

Step 1: Open your note pad and type in this statement.


Msgbox “This is First VB Script”


Step 2: Click File > Save As and in the Save window


1. Enter the fine name as sample.vbs
2. Choose “All Files” option for the Save as Type
3. Click Save button

Step 3: On the desktop or the location you have given you will see a file with this icon

Step 4: Double clicking on this file your message box will be displayed with the predefined message you gave “This is First VB Script”

Let’s understand what Msgbox function does

Msgbox is used for displaying the output. It is an inbuilt VB function used to output (display) a value to the user. This value can be a constant or a variable. Msgbox contains a OK button. Until the user clicks the OK button the execution will not move on to the next line.

Previous12345678910Next