VB Scripting - Important Terminology Before actually looking into VB scripting it is good to understand some terminology and also what
they mean. We should know some thing about programming, scripting, compiler, scripting to have a better understanding.
Let’s look at what Programming and Scripting means
Programming: Programming is used for application development and involves writing of code and should have in depth knowledge of a programming language. Scripting: Scripting on the other hand does not involve in writing the entire code for the application but involves in writing some lines of code or instructions so as to validate the application developed. To put in simple language Scripting is used for validation.
What is Compiler and Interpreter
Compiler: Programming uses compiler to compiles the entire code in one go creates an executable file. This executable file will be used for execution. advantage of compiler is that it has a faster execution rate compared to interpreter. The big disadvantage of compiler is that there is no way you change your code in the executable file and you have to go back to the code make changes and again create an executable file. and The the can and
Interpreter: Scripting uses Interpreter to read the code one line at a time and executes one line at a time. The advantage is that if the interpreter encounters an error it stops executing the remaining lines and you have the chance to correct it and re run it. At any point of time you can interrupt wile running and change the code and continue running it. The biggest disadvantage is that each time the code is executed it has to read each line and is time consuming and is also slow.
What is VB Script? 1. VB Script is a scripting language. 2. A scripting language is a lightweight programming language. 3. VB Script is a subset of Microsoft's programming language Visual Basic. 4. VB Script is not case sensitive but as a part of best coding standards we use appropriate casing.
How to create and run a VB script?
It is very simple to create a VB script. Just write the code in a Microsoft Note pad and save the file by giving the file name with an .vbs extension. For example in the File name text box while saving you can enter this file name “example1.vbs”. In the Save as File choose the option “All Files” other wise it will save as a text file. As soon as you save your file as a VB script file you can run the script by double clicking on it.
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.
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”
UserInput = Inputbox(“Please Enter your Name”)
When you execute the file by double clicking it is displayed like this. 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. Msgbox contains a OK button.
Type in the statement below in your note pad and save as sample2. It is an inbuilt VB function used to output (display) a value to the user.Let’s understand what Msgbox function does
Msgbox is used for displaying the output.
Input box function in VB Scripting is used to get information from the user and then that value is stored in a variable. Until the user clicks the OK button the execution will not move on to the next line. In order to do this modify your code like this
UserInput = Inputbox(“Please Enter your Name”) Msgbox "UserInput"
“UserInput” in the above statement is a variable and whatever the user enters in the text box is stored in the variable called “UserInput”. This value can be a constant or a variable.
. Operators like =. String. Conversion.
. Date and Time 7.* etc. 2.
VB Scripting has some building blocks and are important to know them and use them in an appropriate manner. Looping Constructs (For loop. Variable has something called as data types. To put in as a definition Input box is an inbuilt VB Scrip function used for getting an input from the user during runtime.
1. When the user clicks the OK button this data is assigned to a variable.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.-. File System Object
What is a Variable?
Variable in VB Script is a place holder in the memory used to store some data or information. Input box provides a text box and allows the user to type in some data. While loop) 5. The default input type for an input box is a string. Below are given the building blocks used in VB Scripting. 3. Functions and Procedures 6. Branching statements to make decisions (If then else conditions) 4.+.
The information stored in the memory is not permanent. The Memory used is temporary. Explicit Declaration. Below are the basic rules followed while creating a Variable.ImplicitDeclaration. *. 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. -.
Implicit Declaration is a default declaration type in VB and there is no need for us to declare a variable before assigning a value
.The information assigned in the variable is a reserved section in the computer’s memory for storing data.
Rules for VBScript Variable usage
A variable in the VB script cannot start with a numeric value (Ex – 1stvalue).) or arithmetic operators (+. It can be a combination of Alphabets and Numbers together (Value1) or separated by a underscore (Value_1). 2. ^) The max length of the variable is 256 characters
Types of Variable Declaration
In VB Script Variable Declaration happens in two ways:
From the above we can see that = is an assignment operator.
• • •
It must always begin with a letter Should not contain a period (. /.
Assigning values to a Variable
A value to a variable can be assigned either using Implicit Declaration or Explicit Declaration. 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.
. We should be careful in using the Implicit Declarations.
From the above example Int1 and Int2 are operands and the * is the operator and = is the assignment operator.
Implicit declaration is easy to use. With this type of declaration it is easy to create variables as and when required. 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. Int2. Int1. We don’t need to keep track of the variables used in the VB script. The declaration and definition happens in one step. Example
Int1 = 28 Int2 = 30 Prod = Int1 * Int2 Msgbox Prod
Let’s see how this is stored in the memory. 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).to the variable.
Prod Int1 = 28 Int2 = 30 Prod = Int1 * Int2 Msgbox Prod Now lets debug the code.
This is the advantage of using Explicit Declaration. In order to create Explicit Declaration in the beginning of the code we need to add one more line of code as ‘Option Explicit”. If by mistake instead of “Prod” you type “Prd” in Line 6 as Msgbox Prd then what will happen. 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. Int2. 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. Take a look at the code for Explicit Declaration Option Explicit Dim Int1.
We will use the same example used for Implicit Declaration but will change the script.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.
. It will throw error as “Variable is undefined: ‘Prd’.
401298E45 for negative values and for positive values is from 1.767. 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.147.
A Variant can hold data which contains either a numeric or a string value. String.94065645841247E-324 for negative values and for positive values is from 4.768 to 32.483. floating point range is from -1. Below table gives a clear picture of subtypes of data which a Variant can hold or contain.
.147.402823E38 to -1.402823E38.401298E-45 to 3.94065645841247E-324 to 1.648 to 2.79769313486232E308. The Variant behaves in the way you want i. Holds big precision.What are the Data Types in VB Script?
Data types in VB Script is used in context of Variable. The only difference is that any data which is enclosed in quotation marks (" ") behaves like a string even though it contains only numbers. Long is for numbering system. Long. Holds small precision. There is only one data type in VB Script called as Variant.
Variant can hold any type of data like Integer. The Integer range is from -32.
Subtype Integer Long Single Description The size is of 2 bytes.483. Value can be from 0 to 255.647. Single or double etc. The different categories of information/data which a Variant can hold are called as subtypes.79769313486232E308 to -4. behaves as a numeric value when used in a numeric context and behaves like a string when used in a string context. The Integer range is from -2.e. floating point range is from -3.
477.5808 to 922. Contains integer in the range 0 to 255. Value is 0 for numeric variables or a zero-length string ("") for string variables.
You can use the conversion functions to convert the data from one subtype to another subtype which will be discussed in Type Cast lesson.Currency Date (Time) Object Boolean Empty Null Byte
Ranges from -922.477.
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. 100 to December 31.685. Contains an object. Relational or Comparison Operators.337. 9999. Contains a boolean value either True or False.685. Operator is a notation to perform operation and this operation will happen on one or more operands.
.5807. Concatenation Operator. Variant is uninitialized. The range is between January 1.203.203.
Operators in VB script can be classified in to mainly four. Logical Operators.337. Variant intentionally contains no valid data. They are
• • • •
5 2 25 1
Logical operators are used to perform logical operations. Please find the list of Operators with some examples for easy understanding. Multiplication and other kinds of operations. Please find the list of Operators with some examples for easy understanding.
Operator Not Or And English Meaning Inverts Value Either Can Be True Both Must Be True Example Not False True or False True And False Result True True 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. They are used to manipulate statements or create logical expressions. Subtraction.VB Script – Arithmetic Operators
Arithmetic operators are used for arithmetic operations or mathematical operations such as Addition. The Logical operators are AND. OR and NOT.
Operator = > < >= <= <> English Meaning Equal To Greater Than Less Than Greater Than or Equal To Less Than or Equal To Not Equal To Example 20 = 45 20 > 45 20 <> 20 >= 45 20 <= 45 20 <> 45 Result False False True False True True
Operator + * / \ ^ Mod English Meaning Add Subtract Multiply Floating Point Division Integer Division Exponent Modulus Example 5+2 5-2 5*2 5/2 5\2 5^2 5 Mod 2 Result 7 3 10 2. Please find the list of Operators with some examples for easy understanding.
This would help us to validate different conditions for one expression. 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. Switch Case
. Please find below the description with examples for easy understanding. Using these branching statements you can branch out your code to different conditions. We use “&” to join two expressions.
Operator English Meaning & Join or Connect Example "Hello" & "World" Result Hello World
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. 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. If Elseif 3.
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.Concatenation Operator
In order to combine two strings and display as a single string we use Concatenation Operator (&). For example take this scenario of giving different grades to a student based on the percentage. If Else 2. Basically there are three types of Branching Statements
Endif Else and Elseif are used to branch out different conditions.Out of these the popular branching or conditional statement used is the If Else.
'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.
If Else statement in VB script is used when you want to execute a block of code based on certain condition." End If
If the user enters 85 then the output displayed will be
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.
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.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.
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. We will calculate the average for three subjects and based on the percentage we will display the average and the appropriate messages.
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.
To do this you need Else If statement.
'Calculating the average for three subjects mt = Inputbox("Enter the marks scored for Manual Testing:") qtp = Inputbox("Enter the marks scored for QTP:")
Let me explain you what happened so that we will be clear as to what happened and how to rectify the code.333333333333 and the first message will be displayed which is wrong. 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. Let’s debug the script line by line.
. That is the reason we are getting a different result.
mt=3. qtp=0.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. sql=1 avg=(mt+qtp+sql)/3 avg=(3+0+1)/3 avg 301/3 avg=100.
Note: You can also use CINT on the expression instead on inputbox. (CINT(mt)+CINT(qtp)+CINT(sql))\3 Assignments on Else If Statement
. It will look like this. For this we need to use CINT.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. 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. You cannot use CINT for some variables while accepting values and for some on the expression. CINT can be used with input box or while on the expression calculating the average (In our case).
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
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
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
Const GREETING = “Welcome to VB Scripting” Msgbox GREETING
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.
The message box displayed will be like this with Yes and No buttons. the current application will not work until the user responds to the message box System modal i.e. all applications wont work until the user responds to the message box What it does
Const TEST = "Are you sure you want to exit" msgbox TEST. No. and Ignore buttons Yes.Different types of Built in Constants Please find the list of built in constant and their meaning.
Built in Constants vbOKOnly vbOKCancel vbAbortRetryIgnore vbYesNoCancel vbYesNo vbRetryCancel vbCritical vbQuestion vbExclamation vbInformation vbDefaultButton1 vbDefaultButton2 vbDefaultButton3 vbDefaultButton4 vbApplicationModal vbSystemModal OK button only OK and Cancel buttons Abort. and Cancel buttons Yes and No buttons Retry and Cancel buttons Critical Message icon Warning Query icon Warning Message icon Information Message icon First button is default Second button is default Third button is default Fourth button is default Application modal i.e.
FOR Looping Construct Example
. For Each Next
DO looping Constructs
1. Also there are those loops which repeat statements for a specific number of times.
Looping constructs allows a user to run a group of statements or piece of code repeatedly that many times as desired by the user. For Next Loop 2. Do Loop While 2.Different types of Looping Constructs in VB Script and its usage in VB Scripting. While WEnd Loop
FOR Looping Constructs in VB Scripting
For Loop is used to run a piece of code iteratively for a finite number of times. Do Until Loop 5. The start and end conditions are known in advance and the counter automatically increments by one and this increment is by default. Let’s look at them FOR Looping Construct
1. For Step Next Loop 3. The are basically two types of looping constructs FOR and DO. There are some loops which repeat statements until the condition become false and others loops which repeat statements until the condition becomes true. There are different kinds of looping construct and based on the requirements we can use any of this Looping constructs. Do Loop Until 3. Do While Loop 4.
Assignment to do for FOR Looping Construct
1. To change the default increment value we use “STEP” along with the For Loop or you can have user defined increment like i=i+1 etc.
For Step Next Looping Construct
In this kind of looping construct we actually change the increment to the desired number and the increment happens as we desire.7.For [condition] Code Next
A simple for loop example
For i = 1 to 10 Msgbox "This loop is repeated "&i& " times" Next
When you run this script the message box will display “This loop is repeated 1 times” and as you click the number increments till it reaches 10 times and also in the message the number is incremented and displayed.5.9 and the script terminates because next value is 11 and is greater than 10. Now using the For loop try to ask the user
For [condition] Step [increment/expression] Code Next
Example: We will use the above example and change the increment value as desired. subtraction. multiplication and division.
For i = 1 to 10 Step 2 Msgbox "This loop is repeated "&i& " times" Next
Now when you run the script the value is incremented by 2 and the value in the message box will change and will display as “This loop is repeated 1 times” initially and then the value changes to 3. Hope you remember the SELECT CASE statement in which we have looked at a code where in the user can perform a particular type of operation like addition.
Procedure is a named block of code used for performing a specific task. Syntax
Function [name](arguments) Code Code End Function Functions in VB Script
Functions helps us to avoid using the same piece of code at different places making the code bulky instead putting this piece of code in a function and calling it would solve all the issues and also it maintainable. Again ask the user for the limit. Write a script to print all the odd numbers till 100. Write a script to generate the Fibonacci series. Look Click the script Here for to this Select view Case the Statement Answer
2. For ex if the user enters 3 then the code should run for three times.
1. Click Here to view the Answer
3. Write a script to convert degrees to Fahrenheit. Functions are of two types.how many times the operation should perform. Click Here to view the Answer
4. Do not use the STEP statement.
Functions and Procedures in VB Script are used to make the task very easy for the user. In built Functions 2. Procedures help us to break a complex architecture into reusable blocks and yields modularity. Write a script to print prime numbers based on the user input for the prime number limit. User Defined Functions
In built Functions are those which are already loaded in the VB Script Library while User Defined Functions are those which the user defines for specific task. byVal is known as Passby. a function or procedure returns a value to the calling function while a sub procedure does not return a value. Int1 and Int2 are called as arguments. To put in general A procedure returning a value is called function procedure.
User Defined Function Example Function Multiply(byVal Int1. The Variable Multiply is known as Function Name.
A procedure which does not return a value is called Sub Procedure. End Function marks the end of the Function and the whole piece of code is known as Function Definition. Generally a function is written to perform a single function i.4
When this script is run the function returns a value of 12.e. There is a difference between a Function or Procedure and a sub procedure. Let us understand what a Function call is and why a Function Call is used.
In order to execute a Function we need to call that function at a point in our script and this is called Function call. one specific task at a time. The whole Function what we write is called a
What is a Function Call in VB Script?
In continuation with the previous discussion of Functions and Procedures in VB Script. byVal Int2) Prod = Int1*Int2 End Function Multiply 3. The code within the Function name and End Function is called the Function Body.
Function Definition and if a piece of code which is converted into a function will not get executed unless we create a call to the function.
Procedure Level Variables are also called as Local Variables because they can only be used in the Procedure or Function.
Defining the Scope of a Variable in VB Script
Variables in VB Script is used for assigning values and using them for different operations. Why is it so? The answer is that since we know the requirements and know how many variables or in this context arguments we use in the function we should define a function and then write the Function Call because we will use these arguments in the Function Call. The scope of a variable determines where it should be used in the script.
In any programming language there is a scope for everything used in the code and likewise in VB scripting also there is a scope for a variable. VB Script searches first the function and then goes and Function Definition and executes the function. The scope of a variable is of two types. Script Level Variable. If a variable exists within a function then it works for that function meaning it is used within the function and the value gets destroyed once it comes out of the function. This is a general rule that the Function Definition should happen first and then the Function Call. Procedure Level Variable. Function call can happen any where in the script. The scope of a variable depends on its declaration in the script. So to put in a simple way we need to call the functions which we write in the script other wise it is just occupying some lines of code and makes no sense. ease of understanding. The scope of Variable in VB Script can be classified as Local Variable and Global Variable. A function can have zero or more arguments. Function definition can happen any where in the script but as per coding standards the Function Calls should be at one place before the Function Definitions and these should also be at one place for maintainability. Script Level variables are also called as Global Variables and they can be called anywhere in the script. These variables can be used even in the Functions but
Passing an argument by value using byval in VB creates a copy of the variable. These Script Level variables are always declared out side the procedures. First the x is assigned as 20 and the msgbox in the second line prints 20.based on the passby values. The scope of this new variable is local to the function which implies that this variable will be destroyed at the end of the function.
x=CINT(Inputbox20("Enter any Value")) aaamsgbox "The value outside the function is: "&x myfunc x aaamsgbox "The value which is again outside the function is: "&x Function myfunc (byval x) aaax=30 aaamsgbox "The value inside the function is: "&x End Function
Let’s debug line by line. If a variable is passed as an argument by value then a copy of that variable is created in the memory and is passed into the function. Lets look at one example to understand what it means by byval or passing an argument by value.
The value inside the function is: 30
The scope of a variable can be changed in VB Script using parameters associated with the arguments.
The value outside the function is: 20
Then the ‘myfunc’ function is called in line 3 and this function call executes the function from line 5. Since in the Function definition locally we have assigned x value as 30 so the msgbox will print 30 and the function is terminated.
An argument is always defined by parameters either by reference or by value depending upon how it is declared in the function or procedure.
byval Int2) aaamultiply = Int1*Int2 End Function aaamsgbox "The product of Value one and two is: "&multiply(Int1.
The value which is again outside the function is: 20
Let us look at another example where you can use the name of the function as a variable name inside the function definition and call that function.
You can write in this way by assigning the function call to a variable and then passing the variable in the msgbox to print the value.Then the line 4 which is after the function call ‘myfunc’ is executed and the msgbox prints x value as 20 because the local variable x value is overwritten with the global value and prints 20. The modified code will be like this
Int1=CINT(Inputbox("Enter value one")) Int2=CINT(Inputbox("Enter value two")) Function multiply(byval Int1. Passing an argument by reference using byref in VB will destroy the previous assigned value to the variable.Int2) aaamsgbox"The product of Value one and two is: "&x
The scope of a variable can be changed in VB Script using parameters associated with the arguments.
Int1=CINT(Inputbox("Enter value one")) Int2=CINT(Inputbox("Enter value two")) Function multiply(byval Int1. byval Int2) aaamultiply = Int1*Int2 End Function x = multiply(Int1.
If the value of that variable is changed inside the function it would impact the original value. If a value is passed into a function as an argument by reference then the value of that variable is passed to the function.An argument is always defined by parameters either by reference or by value depending upon how it is declared in the function or procedure.
x= CINT(Inputbox("Enter a number")) aaamsgbox "The value outside the function is: "&x myfunc x aaamsgbox "The value which is again outside the function is: "&x Function myfunc (byref x) aaax=30 aaamsgbox "The value inside the function is: "&x End Function
First the x is assigned as 20 and the msgbox in the second line prints 20. Since in the Function definition locally we have assigned x value as 30 so the msgbox will print 30 and the function is terminated. Since we are using the argument by reference after the function is called the value of x is 30 and since it is by reference the value of x permanently becomes 30
The value which is again outside the function is: 30
Another way of calling an argument value by reference
. Let’s take an example and try to understand what happens when a value to an argument is passed by reference. In other words the original value is replaced by this value.
The value outside the function is: 20
Then the ‘myfunc’ function is called in line 3 and this function call executes the function from line 5.
The value inside the function is: 30
Then the line 4 which is after the function call ‘myfunc’ is executed and the msgbox prints x value as 30 because the global variable x value is overwritten with the local value and prints 30.
Create Function calls and then Use Select Case to select the particular function based on the user choice. Folders and Drives with the help of FileSystemObject using VB Script. It is possible to get different kind of information on Files.
What is a File System Object
File System Object or FileSystemObject helps us to deal with Files. VB Script can talk to any of the libraries like FileSystemObject. Like wise VB Script can interact with different libraries and call them using different objects. byref prod) aaaProd = Int1*Int2 End Function Multiply Int1. Using FileSystemObject in VB Script we can create a File. Excel etc. VB Script needs to call the FileSystemObject Library. This is referred to as Component Object Model or COM Look at the Component Object Model or COM figure. Odd number generation. Yo u can also Delete a File.
We can interact with FileSystemObject using VB Script and can perform different kinds of operations as we desire. Int2. You can also write data or information in a File. Multiplication etc using functions in VB Script. Folder.
. conversion from centigrade to Fahrenheit. FileSystemObject is a separate library and not included in VB Script Library. We generate Scripts using VB to interact with them. Word. Note: Use Inputbox to as the user choice to perform what operation is required. Folders and Drives using VB Script. Prime number Generation. Addition. Folders or data in VB using FileSystemObject.Int1=CINT(Inputbox("Enter value one")) Int2=CINT(Inputbox("Enter value two")) Function multiply (byval Int1. byval Int2. x aaamsgbox"The product of Value one and two is: "&x
Assignment: Convert all the previous written scripts like Fibonacci series.
Date of Birth. 4. Objects have properties and Methods.
Classes are of two types. 3. Properties for the above object can be Name. 2. Weight. Now each of this Object (individual) has some properties and Methods. Let us see what an Object contains. 1. Properties define characteristics of an Object.What is an Object?
Let’s spend some time in understanding what is a class. Class is a collection of objects which has properties and methods. Let’s take an example of a Class Room. Methods are the actions performed by the Objects. Let’s say that we have two classes named Male and Female.
. object. 2. Height. 1. An object is an instance of a Class. We cannot make any changes to them. User Defined Class: These are define d by the user for specific tasks. All the individuals are Objects and they fall into either of the class. For Example: Date of Birth cannot be changed while height and weight can be changed or even the name. Color and some properties are Read Only which cannot be changed while some others can be changed. Standard Class: which are loaded in the Library or which are predefined and we just need to call them and use them.
Set Fso = CreateObject("Scripting.
In order to call from FileSystemObject (FSO) Library we first need to create and Object Variable. There is a process in calling a FileSystemObject Object and use it in the VB script to get the desired output. To interact with different libraries we need to create Objects and these Objects are used along with different Methods to perform different operations. Eating.Methods for the above Object can be Sleeping. playing etc which are actions performed by the Object.FileSystemObject")
Here we are creating an object to call a method from the File System Object Library
. Let us look at some examples to create Object to use from different Libraries.
How to call from FileSystemObject Library
For us to write VB scripts for QTP we generally interact with FileSystemObject and Excel Objects. An Object Variable is a Variant with sub type which holds an Object and should be prefixed with a Key word called "SET".
Here we are creating an object to call a method from the Microsoft Word Library
Set OutlookObj = CreateObject("OutLook.Application")
Here we are creating an object to call a method from the Quick Test Library
Set doc = CreateObject("Word. How to display File Properties in VB script? Click Here for the Code
VB Script Examples
VB Script using Excel Library Methods and Properties
. How to Create a Text File using VB Script? Click Here for the Code 2. 1. How to create a Folder using VB script? Click Here for the Code 4.Set xlapp = CreateObject("Excel.Application")
Here we are creating an object to call a method from the Excel Library
Set IE = CreateObject("InternetExplorer.Application")
Here we are creating an object to call a method from the Outlook Library All the above variables are used as a standard convention to understand as to what the object is doing.Application")
Here we are creating an object to call a method from the Internet Explorer Library
Set QtpApp = CreateObject("QuickTest. How to create multiple Text Files? Click Here for the Code 3. Please look at the following scripts where File System Object is used in VB Script for various purposes.
1).font.cells(i.bold=TRUE wsheet.1).Quit 'Releasing the objects Set wsheet=Nothing Set wbook=Nothing Set xlapp = Nothing
Once you run this script go to the folder where the excel workbook is created and open and see how it looks like.cells(i.SaveAs "F:\Textexcel.colorindex=i wsheet.xls" wbook.value = "The code of this color is: "&i wsheet.worksheets(1) 'Here we are adding the data in first column and color in second column For i = 1 to 56 wsheet.Size = 14 wsheet.1).Write a Script to create a workbook and create a worksheet and add information in the cells in VB script using Excel Library.workbooks.2).
'Create an Object variable to interact with Excel Library Set xlapp = CreateObject("Excel.font.Add 'Create a pointer to the first sheet in the workbook Set wsheet = xlapp.1).Close xlapp.interior.colorindex=i Next wbook.
The Script to create a workbook and worksheets with cells is given below.Application") 'Create New Excel Workbook using the xlapp object Set wbook = xlapp.1).font.cells(i.cells(i.cells(i.font.cells(i. The work sheet now contains information in two columns and in the Cell (1.1) you will find the value as The code of this color is 1 in
.Name = "Verdana" wsheet.
black color and in bold and in the cell (1. You can manipulate the cells or using the wsheet.2) you will find the cell filled with black color and like wise till row number 56. The challenge lies in writing a VB script without using any built in functions of VB Script.
a = cint(Inputbox("Enter a number to check whether it is a prime number or not")) count = 0 b=1 Do while b<=a aaaif a mod b = 0 Then aaaaaacount = count +1 aaaEnd If b=b+1 Loop If count = 2 Then aaamsgbox "The number "&a& " is a prime number" Else aaamsgbox "The number "&a& " is not a prime number" End if
val=Inputbox("Please enter any number") valprime = 0 For i=2 to Int(val/2) aaaIf val mod I = 0 Then aaamsgbox "The number"&val&" is not a prime number" aaavalprime=1
Write a VB Script to check whether a given number is prime or not?
We can use a For Next Loop or Do While Loop to check whether a number given is a prime number or not in VB Script.columns) syntax.
MyStr = InputBox(“Enter a string to be reversed”) y = Len(MyStr) For x = y To 1 Step -1 aaachar = Mid(MyStr. In the method one we will find the length of the string and store in y variable and then use a for loop in a descending order and give step as -1.1) aaaNewStr = NewStr & char Next aaamsgbox newstr
Method 2 using the StrReverse Method.x.aaaExit for End If Next If valprime=0 Then aaamsgbox "The number"&val&" is a prime number" End If
Write a Script in VB to reverse a string given by the user
This VB Script demonstrates how we can reverse a string or a number given by the user and print it in a reverse order.
val=Inputbox("Please enter any number or a string") a = strReverse(val) msgbox "The reverse of "&val& " is: "&a
. Here we use Len and Mid methods of VB Script library.
FileSystemObject") Set Fil = FSO. 1) Do Until Fil.txt".Close For l = Ubound(arrLines) to LBound(arrLines) Step -1 aaastr = str&arrLines(l)&vbnewline Next msgbox str
Write a Script to print the phone list in VB Script using Arrays dynamically
Dim arrLines() i=0 Set FSO = CreateObject("Scripting.AtEndOfStream aaaRedim Preserve arrLines(i) aaaarrLines(i) = Fil.ReadLine aaai = i + 1 Loop Fil.OpenTextFile("F:\TestFolder\Text1.Write a VB script to print a Text File in reverse way i.e the lines begins with the last line in the text file and ends with the first line as the last line.e from the Last line to first line
This VB scripts demonstrates on using the FileSystemObject to read a text file and display the lines in the text file in a reverse order i.
vbs file and execute it. The script in VB looks like this.k)&vbnewline Next aaaMsgbox "The Phone List is "&vbnewline&str
.row) For i = 0 to row aaaFor j = 0 to col aaaaaaArrphonelist(j.i) = InputBox("Enter the First name") aaaaaaaaaj=j+1 aaaaaaArrphonelist(j.
Here we are using a Dynamic array because we do not know the lower and upper bound of the array and the user enters the column and row count for the array.
Method 1 for writing the script col = InputBox("Enter the number of Columns") row = InputBox("Enter the number of Rows") Dim arrphonelist() ReDim arrphonelist(col. Also we are asking the user to give input the field values for the array.2) For k = 0 to arrubound aaastr = str&arrphonelist(0.i) = InputBox("Enter the Phone Number") aaaNext Next arrubound = ubound(arrphonelist.Write a Script to print the phone list in VB Script using Arrays dynamically. You can copy the script and paste it in a notepad and save as a .k)&" " aaastr = str&arrphonelist(1.i) = InputBox("Enter the Last name") aaaaaaaaaj=j+1 aaaaaaArrphonelist(j.k)&" " aaastr = str&arrphonelist(2.
k)&vbnewline Next aaaMsgbox "The Phone List is "&vbnewline&str
Write a Script to print a Phone List in VB using Arrays
.k)&" " aaastr = str&arrphonelist(1.i) = InputBox("Enter the Phone Number") aaaNext Next arrubound = ubound(arrphonelist.row) For i = 0 to row -1 aaaFor j = 0 to 2 aaaaaaArrphonelist(0.i) = InputBox("Enter the First name") aaaaaaaaaj=j+1 aaaaaaArrphonelist(1.i) = InputBox("Enter the Last name") aaaaaaaaaj=j+1 aaaaaaArrphonelist(2.k)&" " aaastr = str&arrphonelist(2.2) For k = 0 to arrubound aaastr = str&arrphonelist(0.Method 2 where we only ask the number of rows and keep the columns fixed to 3 row = InputBox("Enter the number of Rows") Dim arrphonelist() ReDim arrphonelist(2.
0) = "9854685623" Arrphonelist(0.3) 'Giving all the values of different columns for the 4 rows. Also we are giving the array values.0) = "John" Arrphonelist(1.2) = "Marshal" Arrphonelist(2.
'Initializing an array with 3 columns and 4 rows Dim arrphonelist(2.1) = "Mark" Arrphonelist(1. The script in VB looks like this. Arrphonelist(0. You can copy the script and paste it in a notepad and save as a . You have to remember that the column and Row count in VB using Arrays start by default with zero and hence for 3 columns we are giving 2 because 0 to 2 makes it 3 columns and like wise for rows.0) = "Abharam" Arrphonelist(2.2) = "8080454525" Arrphonelist(0.
Here we are using a static array because we are giving the lowerbound and upperbound of the array.2)
.1) = "Robin" Arrphonelist(2.3) = "Blackston" Arrphonelist(2.vbs file and execute it.3) = "Alex" Arrphonelist(1.2) = "Peter" Arrphonelist(1.Write a Script to print the phone list in VB Script using Arrays.1) = "9955662233" Arrphonelist(0.3) = "9865653526" 'Initializing the upperbound of the array for checking the no of rows 'for this we have entered 2 which represents the 2nd dimension arrubound = ubound(arrphonelist.
OpenTextFile("F:\TestFolder\Text1.txt". 1) x=1 Do Until File.
Set objExcel = CreateObject("Excel.i)&" " aaastr = str&arrphonelist(1.i)&vbnewline Next aaaMsgbox "The Phone List is "&vbnewline&str
How to print all the Lines of a Text File in Excel sheet using VB Script
Write a script in VB to write all the lines of a Text File into an excel spreadsheet using FileSystemObject
VB Script to write all the lines of a text file in to a Excel spread sheet.For i = 0 to arrubound aaastr = str&arrphonelist(0.FileSystemObject") Set file = FSO. There are two ways to write all the lines by opening an existing Text File and the second one to create a Text File and write some lines and then writing them in the Excel Sheet.AtEndOfStream Line = File.Visible=True objExcel.workbooks.Add() Const ForReading =1 Set FSO = CreateObject("Scripting.i)&" " aaastr = str&arrphonelist(2.ReadLine
ReadLine xlapp.xls" set wbook=nothing xlapp.Workbooks. False) X=1 Do Until fil1.FileSystemObject") Set xlapp = CreateObject("Excel.1) = Line x=x+1 Loop objFile.Cells(x.worksheets(1) 'Write few lines into the first text file For i = 1 to 100 fil.AtEndOfStream strLine = fil1.Add set wsheet = xlapp.Close
'Script to create and write few lines in a Text file 'and write them in the excel sheet 'Create an object variable to interact with the File System Object Set Fso = CreateObject("Scripting.txt".1.Cells(x.Application") 'Create a text files using CreateTextFile method Set fil = Fso.WriteLine("This is Line "&i) Next Set fil = nothing 'Open first text file in read mode and write in excel sheet Set fil1 = fso.SaveAs "F:\TestFolder\Test.OpenTextFile("F:\TestFolder\Text1.txt") Set wbook = xlapp.objExcel.quit
.1) = strLine X=x+1 Loop wbook.CreateTextFile("F:\TestFolder\Text1.
set wsheet = nothing Set fil = nothing Set fil1=Nothing Set fil2 = nothing
Write a script in VB to display only the Text Files in a Folder using FileSystemObject
VB Script used to display only the Text files of a Folder by using the GetFolder and Files method and also arrays to print all the Text Files.Files 'Print only the text file names from the specified folder For each f in fil str = f.
'Step 1: Create and object variable to interact with the File system object Set fso = CreateObject("Scripting.name arr = split(str.name End If Next msgbox "The Text Files in the Folder "TestFolder" are: "&vbnewline&var
.GetFolder("F:\TestFolder") 'Step 3: Return all the files collection from the specified folder Set fil = Fol. ".") If arr(1) = "txt" then var = var&Vbnewline&f.FileSystemObject") 'Step 2: Point to the folder from which we want to print 'the file names Set fol = fso.
'Step 1: Create and object variable to interact with the File system object Set fso=createobject("Scripting.FileSystemObject") 'Step 2: Point to the folder from which we want to print the file names Set fol = fso.How to display all the files in a Folder in VB Script Write a script in VB to display all the files in a Folder using FileSystemObject The VB Script to display all the files of a Folder uses the GetFolder and Files method to print all the files.GetFolder("F:\YouTube Downloader") 'Step 3: Return all the files collection from the specified folder Set fil = fol.files 'Print all the file names from the specified folder For each f in fil str = str&" "&f. " Next Msgbox The files in the Folder YouTube Downloader are " &Vbnewline&str
Write a Sample VB script using Arrays
When we declared the array and assigned the values we are now assigning the array upperbound to a variable so that using that variable we can use a for loop to print all the values.Write a VB script using Array to print different color Names.
Dim arrcolors(5) aaaarrcolors(0) aaaarrcolors(1) aaaarrcolors(2) aaaarrcolors(3) aaaarrcolors(4) aaaarrcolors(5)
= = = = = =
"Blue" "Green" "Red" "White" "Black" "Yellow"
arrubound = ubound(arrcolors) aaamsgbox arrubound aaaaaaFor i = 0 to arrubound aaaaaaaaamsgbox arrcolors(i) aaaaaaNext aaaaaaFor each element in arrcolors aaaaaaaaamsgbox element aaaaaaNext
Excel Parameters in VB Scripting To interact with Excel Library from VB Script we need to create an object which points to the excel library from VB Script.
Here we declared an Array and indexed it to 6 columns even though we gave the index as 5. we need to remember that in VB the index starts from zero.
worksheets(1) Set wsheet = xlapp. The syntax to add a workbook is
Set [Variable] = Object.Application")
To Create a new workbook we need to use this syntax. The syntax to open an existing workbook is
Set [Variable] = Object. Workbooks Method is used to point to a work book. Worksheet method is used to point to a worksheet.Add
To Open an existing workbook we need to use this syntax.worksheets("Testing")
Here id can be the sheet id and the index begin with 1.Workbooks. To close a Work book the syntax is
.Let us look at some of the common methods used to deal with Excel Library.xls")
Every time a workbook is created or opened it should be closed and to close the workbook we need a Close Method.SaveAs () wbook. Before creating a Workbook or worksheet we need to create an Object to interact with Excel Library.Workbooks.Add Set wbook = xlapp.Open () Set wbook = xlapp.SaveAs(("F:\TestFolder\Test.Open("F:\TestFolder ")
To create a worksheet in the workbook we use this syntax and the syntax to create a worksheet is
Set [Variable] = Object.Workbooks.Application") Set xlapp = CreateObject("Excel. To save a new workbook in a destination we use this syntax
Variable.Workbooks.worksheets(id) Set wsheet = xlapp. You can also give a string for the id but should be enclosed in " ". The syntax to create an object is
Set [Object] = CreateObject("Excel.
Writing a VB Script using WriteLine and ReadLine Methods of FileSystemObject to generate the required result 'Script to create two text files. To clear the variable used from the memory we use the Nothing Method. The syntax is
Each Cell is identified with Row and Column as (Row.Quit
As soon as the application is quit it is required to clear the variables so that it does not interfere with other scripts. The syntax is
Set [Object] = Nothing Set wsheet = Nothing Set wbook = Nothing Set xlapp = Nothing
To create cells in the worksheet we use this syntax
wsheet. It is important that the worksheet. excel application variables should be cleared.
Script to create a file and add odd line to second file
Write a Script to create two text files and write some lines in the first file and copy the odd lines of the first file in to the second file.Close wbook. 'Copy all the odd lines from the 'first text file to the second text file
.cells(rows.Quit Xlapp. 'Write few lines into the first text file. Column) Check this script to understand how these methods are used. workbook.Close
It is a good practice to quit the application once your work is over and to quit the excel application we need a Quit Method.cells(1.columns) wsheet.Variable.
txt".txt") Fso.line If Line_number MOD 2 <> 0 Then fil2.OpenTextFile("F:\Text2.AtEndOfStream Line_number = fil1.OpenTextFile("F:\Text1.ReadLine) Else fil1.WriteLine(fil1.txt". False) Set fil2 = fso.FileSystemObject") 'Create Two text files using CreateTextFile method Set fil = Fso.WriteLine("This is Line "&i) Next Set fil = nothing 'Open first text file in read mode and second one in write mode Set fil1 = fso.2. False) 'Scan text file until we reach the endofstream 'Set the line number for every time scanned the file 'if the line number is odd copy in the second file Do While Not fil1.SkipLine End If Loop Set fil = nothing Set fil1=Nothing Set fil2 = nothing
Display of File Properties in VB Scrip using FileSystemObject
Back To File System Object Page
How to display File Properties in VB script?
.1.CreateTextFile("F:\Text1.'Create an object variable to interact with the File System Object Set Fso = CreateObject("Scripting.txt") 'Write few lines into the first text file For i = 1 to 100 fil.CreateTextFile("F:\Text2.
Using the File System Object method CreateFile we create a File and Using the GetFile Method we get the newly created File.CreateTextFile("F:\Text.FileSystemObject") 'Step 2: use the CreateTextFile to Create a Text File Fso.txt") 'Step 3: Use the GetFile Method to get the information of the file and set it to a Object Variable Set F=Fso.DateCreated&""&vbnewline& "The File Last Modified on: "&f. Then we use the name. size etc methods to get the properties of the file.size&""&vbnewline& "The File Creation Date is: "&f.
'Create a Folder using FSO or FileSystemObject 'Script to print the different properties of a Text File 'Step 1: Create an object variable that interacts with the File System Object Library Set Fso = CreateObject("Scripting.txt") 'Step 4: Print the Properties of the File using various MsgBox "The File name is: "&f.DateLastModified
Creating a Folder in VB Script using FileSystemObject
Back To File System Object Page
How to create a Folder using VB script?
.name&"" &vbnewline& "The File Size is: "&f.GetFile("F:\Text.
FileSystemObject") 'Step 2.CreateFolder("F:\Test Folder") 'Step 3: Use the GetFolder method to get the newly created file and store in a variable called s Set s = fso.Using the File System Object method CreateFolder we create a Folder and Using the GetFolder Method we get the newly created Folder.name
Creating multiple Text files in VB Script using FileSystemObject
Back To File System Object Page
How to create multiple Text Files?
.GetFolder("F:\Test Folder") 'Step 4: Use the name method to get the file name and print it along with the message Msgbox "The New Folder Created is "&s. Use the CreateFolder method along with the object to create a Folder at desired location Fso.
'Create a Folder using FSO or FileSystemObject 'Step 1: Create an object variable that interacts with the File System Object Library Set Fso = CreateObject("Scripting.
CreateTextFile("F:\Test"&i&".txt") var = "" &var&".CreateTextFile("F:\Test"&i&". Test" &i Next Msgbox" The Text Files Created are "&Var
.txt") var = "" &var&".FileSystemObject") 'Step 2: Use For Loop to run the script for 100 times.FileSystemObject") 'Step 2: Use For Loop to run the script for 100 times.Using the File System Object method CreateTextFile we create a Text file and using a For Loop we create any number of Text files as desired. Test" &i Next Msgbox" The Text Files Created are "&Var
Example 2: Asking the user for input to print that many number of files. n=CINT(InputBox("Enter how many files to be created")) For I = 1 to n Fso.
Example 1: Assuming we know how many text files to create. Using a InputBox we can also ask the user how many text files to be created. Rewrite the code by just adding one line with InputBox function.
'Create a Text File using FSO or FileSystemObject 'Step 1: Create an object variable that interacts with the File System Object Library Set Fso = CreateObject("Scripting.
'Create a Text File using FSO or FileSystemObject 'Step 1: Create an object variable that interacts with the File System Object Library Set Fso = CreateObject("Scripting. For I = 1 to 5 Fso.
'Create a Text File using FSO or FileSystemObject 'Step 1: Create an object variable that interacts with the File System Object Library. Fso.CreateTextFile("F:\Test.FileSystemObject") 'Step 2: Use the CreateTextFile method along with the object to create a text file at desired location. Set Fso = CreateObject("Scripting.
.txt") 'Step 3: Use the GetFile method to get the newly created file and store in a variable called s.GetFile("F:\Test. Set s = fso.Creating a Text File in VB Script using FileSystemObject
Back To File System Object Page
How to Create a Text File using VB Script? Using the File System Object method CreateTextFile we create a Text file and Using the GetFile Method we get the newly created file.txt") 'Step 4: Use the name method to get the file name and print it along with the message.
Msgbox "The Text Files Created is "&s.Fibonacci Series"&vbnewline&"6 .Subtraction"&vbnewline&"3 . Addition in VB Script. conversion from centigrade to Fahrenheit in VB Script.Multiplication"&vbnewline&"4 . Prime number Generation in VB Script.Prime Numbers"&vbnewline&"8 Degree Conversion")
. The code looks like this Here you are asking the user for the choice to perform the operation.
In order to write this script first we need to use a inputbox to ask the user the choice to perform a certain function.After the Select Case Write down all the Functions for different operations. Then Use Select Case taking the value from Inputbox and based on the condition it will select the case in which the function call is specified.
n=Inputbox("Enter your choice"&vbnewline&" "&vbnewline&"1 Addition"&vbnewline& "2 . Multiplication in VB Script etc using functions in VB Script.name
Assignment Answer on Functions.
Back to the Previous Page
Write a script in VB to Convert all the previous written scripts like Fibonacci series in VB Script. Odd number generation in VB Script.Odd Numbers"&vbnewline&"7 .Quotient"&vbnewline& "5 .
y Case 5 aaaFibonacci var Case 6 aaaoddfunc var Case 7 aaaprime var case 8 aaaconversion cen.y Case 2 aaaminusfunc x.
Select Case n Case 1 aaaaddfunc x. byval y) aaax = CINT(inputbox("Enter 1st number to be added")) aaay = CINT(inputbox("Enter 2nd number to be added")) aaamsgbox "The summation of "&x& " and " &y& " is: " &x+y End Function
For Subtraction of two Numbers
Function minusfunc(byval x.y Case 4 aaaquotient x.Here you are selecting the case based on the user input and appropriately calling the required function. fah Case Else aaamsgbox "invalid entry" End Select
Here you are actually defining the functions for different operations to be performed. byval y) aaax = CINT(inputbox("Enter 1st number")) aaay = CINT(inputbox("Enter 2nd number to be subtracted")) aaamsgbox "The difference between "&x& " and " &y& " is:
.y Case 3 aaamultiply x. For Addition of two Numbers
Function addfunc(byval x.
byval y) aaax = CINT(inputbox("Enter 1st number to be divided")) aaay = CINT(inputbox("Enter 2nd number as divisor")) aaamsgbox "The quotient between "&x& " and " &y& " is: "&x\y End Function
For displaying the Fibonacci Series of a given Number
Function Fibonacci (byval var) aaan = CINT(Inputbox("Enter a range for the Fibonacci Series")) aaaf1=0 aaaf2=1 aaaf3=f1+f2 aaavar= f1& ". "&f3 aaaaaaaaaf1=f2 aaaaaaaaaf2=f3 aaaaaaaaaf3=f1+f2 aaaaaaLoop MsgBox("Fibonacii Series for the limit " &n&" is: " &var) End Function
For displaying the Odd Numbers of a given Number
."&x-y End Function
For Multiplication of two Numbers
Function multiply(byval x. " &f2 aaaaaado while f3 < n aaaaaaaaavar =" var&". byval y) aaax = CINT(inputbox("Enter 1st number to be multiplied")) aaay = CINT(inputbox("Enter 2nd number to be multiplied")) aaamsgbox "The product of "&x& " and " &y& " is: "&x*y End Function
For finding quotient of two Numbers
Function quotient (byval x.
" aaaaaaaaaEnd If aaaNext aaaMsgBox("Prime numbers within " &n&" numbers = :" &var) End Function
For converting from and to Centigrade or Fahrenheit of a given Number
Function conversion(byval cen.Function oddfunc(byval var) aaan = CINT(Inputbox("Enter the limit for the Odd Numbers")) aaaaaaFor i = 1 to n aaaaaaaaaif (i mod 2<>0) then aaaaaaaaavar = "" &var&". " &i aaaaaaaaaEnd If aaaaaanext aaaMsgBox("Odd numbers within " &n&" numbers = :" &var) End Function
For displaying the Prime numbers of a given Number
Function prime(byval var) n = inputbox("Please Enter the limit for Prime Numbers to be printed") aaaFor i = 1 to n aaaaacount = 0 aaaaaa = 1 aaaaaaaDo While a<=i aaaaaaaaaif i mod a = 0 Then aaaaaaaaaaacount = count + 1 aaaaaaaaaend if a=a+1 aaaaaaaLoop aaaaaaaaaIf count = 2 Then aaaaaaaaaaavar = var&" " &i& ".55555555556 + 32& " Fahrenhite" aaaaaCase 2
. byval fah) con = inputbox("Enter 1 for Centigrade to Fahrenheit and 2 for Fahrenheit to Centigrade") aaaSelect Case con aaaaaCase 1 aaaaaaacen=inputbox("Enter the value to be converted") aaaaaaamsgbox "The converted value of " &cen& " Centigrade is " &cen\0.
Again ask the user for the limit. "&f3 f1=f2 f2=f3 f3=f1+f2 loop MsgBox "Fibonacii Series for the limit " &n&" is: " &var
In order to generate a Fibonacci Series in VB Script we make use of the DO WHILE LOOP Looping Construct.
The code for generating the Fibonacci Series is given below. " &f2 do while f3 < n var = var& ".aaaaaaafah=inputbox("Enter the value to be converted") aaaaaaamsgbox "The converted value of " &fah& " Fahrenheit is " &(fah-32) *0.
n = CINT(Inputbox("Enter a range")) f1=0 f2=1 f3=f1+f2 var= f1& ".55555555556 & " Centigrade" aaaaaCase Else aaaaaaamsgbox "Invalid entry for Conversion" aaaEnd Select End Function
Fibonacci Series Code
Click on Back to the Assignment Question Page
Write a script to generate the Fibonacci Series.
34. " aaaaaaaaaEnd If Next aaaMsgBox("Prime numbers within " &n&" numbers = :" &var)
Write a VB Script to Print different Operations using Select Statement
Click on Back to the Assignment Question Page
This Code gives an idea as to how we can use FOR loop in our script to make it more
.55 and 89 if we take the range as 100.3.
Script to print Prime Numbers
Click on Back to the Assignment Question Page
Write a script to print prime numbers based on the user input for the prime number limit.126.96.36.199.1.
n = Inputbox("Please Enter the limit") For i = 1 to n aaaCount = 0 aaaa = 1 aaaaaaDo While a<=i aaaaaaaaaIf i MOD a = 0 Then aaaaaaaaaaaaCount = Count + 1 aaaaaaaaaEnd If aaaaaaa=a+1 aaaaaaLoop aaaaaaaaaIf Count = 2 Then aaaaaaaaaaaavar = var&" "&i& ".5.Till the condition is satisfied the inner conditions get executed and stored in the var variable thus giving out the output as 0.
multiplication and division.
Hope you remember the SELECT CASE statement in which we have looked at a code where in the user can perform a particular type of operation like addition.Var2 aaaCase 3 aaamsgbox"The product of "&Var1& " and " &var2& " is:
Varint1 = CINT(Inputbox("Enter the number of times this operation to be performed")) For i = 1 to Varint1 Step 1
Look at the entire code
Varint1 = CINT(Inputbox("Enter the number of times this operation to be performed")) For i = 1 to Varint1 Step 1 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")) aaaSelect Case UserInput aaaCase 1 aaamsgbox"The Sumation of "&Var1& " and " &var2& " is: "&Var1 + Var2 aaaCase 2 aaamsgbox"The difference between "&Var1& " and " &var2& " is: "&Var1 . subtraction. Now using the For loop try to ask the user how many times the operation should perform. What i have done is that before the user to select the operation before this line we will add few code like an inputbox and a for loop. Now we are asking the user how many times the user wants to perform the operations and taking that value in the variable Varint1 and converting it into integer. Look the script for this Select Case Statement The script for this is given below. For ex if the user enters 3 then the code should run for three times. Then we are passing the value into the for Loop and incrementing by one value. Remember that by default a variant is a string. The code to be added in the top is like this and at the end of the code add NEXT.meaningful and reduce the no of lines of code.
"&Var1 * Var2 aaaCase 4 aaamsgbox"The quotient between "&Var1& " and " &var2& " is: "&Var1 \ Var2 aaaCase Else aaamsgbox "Invalid entry" aaaEnd Select Next