Friday, April 30, 2010
Wednesday, April 28, 2010
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. The challenge lies in writing a VB script without using any built in functions of VB Script.
Method 1
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
Method 2
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
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. Here we use Len and Mid methods of VB Script library. 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.
Method 1
MyStr = InputBox(“Enter a string to be reversed”)
y = Len(MyStr)
For x = y To 1 Step -1
aaachar = Mid(MyStr,x,1)
aaaNewStr = NewStr & char
Next
aaamsgbox newstr
Method 2 using the StrReverse Method.
val=Inputbox("Please enter any number or a string")
a = strReverse(val)
msgbox "The reverse of "&val& " is: "&a
Write a VB script to print a Text File in reverse way i.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.e the lines begins with the last line in the text file and ends with the first line as the last line.
Dim arrLines()
i = 0
Set FSO = CreateObject("Scripting.FileSystemObject")
Set Fil = FSO.OpenTextFile("F:\TestFolder\Text1.txt", 1)
Do Until Fil.AtEndOfStream
aaaRedim Preserve arrLines(i)
aaaarrLines(i) = Fil.ReadLine
aaai = i + 1
Loop
Fil.Close
For l = Ubound(arrLines) to LBound(arrLines) Step -1
aaastr = str&arrLines(l)&vbnewline
Next
msgbox str
Tuesday, April 27, 2010
Write a Script to print the phone list in VB Script using Arrays dynamically
Write a Script to print the phone list in VB Script using Arrays dynamically.
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. Also we are asking the user to give input the field values for the array. The script in VB looks like this. You can copy the script and paste it in a notepad and save as a .vbs file and execute it.
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,row)
For i = 0 to row
aaaFor j = 0 to col
aaaaaaArrphonelist(j,i) = InputBox("Enter the First name")
aaaaaaaaaj=j+1
aaaaaaArrphonelist(j,i) = InputBox("Enter the Last name")
aaaaaaaaaj=j+1
aaaaaaArrphonelist(j,i) = InputBox("Enter the Phone Number")
aaaNext
Next
arrubound = ubound(arrphonelist,2)
For k = 0 to arrubound
aaastr = str&arrphonelist(0,k)&" "
aaastr = str&arrphonelist(1,k)&" "
aaastr = str&arrphonelist(2,k)&vbnewline
Next
aaaMsgbox "The Phone List is "&vbnewline&str
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,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,i) = InputBox("Enter the Phone Number")
aaaNext
Next
arrubound = ubound(arrphonelist,2)
For k = 0 to arrubound
aaastr = str&arrphonelist(0,k)&" "
aaastr = str&arrphonelist(1,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
Write a Script to print the phone list in VB Script using Arrays.
Here we are using a static array because we are giving the lowerbound and upperbound of the array. Also we are giving the array values. The script in VB looks like this. You can copy the script and paste it in a notepad and save as a .vbs file and execute it. 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.
'Initializing an array with 3 columns and 4 rows
Dim arrphonelist(2,3)
'Giving all the values of different columns for the 4 rows.
Arrphonelist(0,0) = "John"
Arrphonelist(1,0) = "Abharam"
Arrphonelist(2,0) = "9854685623"
Arrphonelist(0,1) = "Mark"
Arrphonelist(1,1) = "Robin"
Arrphonelist(2,1) = "9955662233"
Arrphonelist(0,2) = "Peter"
Arrphonelist(1,2) = "Marshal"
Arrphonelist(2,2) = "8080454525"
Arrphonelist(0,3) = "Alex"
Arrphonelist(1,3) = "Blackston"
Arrphonelist(2,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,2)
For i = 0 to arrubound
aaastr = str&arrphonelist(0,i)&" "
aaastr = str&arrphonelist(1,i)&" "
aaastr = str&arrphonelist(2,i)&vbnewline
Next
aaaMsgbox "The Phone List is "&vbnewline&str
Write a Sample VB script using Arrays
Write a VB script using Array to print different color Names.
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. 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.
Dim arrcolors(5)
aaaarrcolors(0) = "Blue"
aaaarrcolors(1) = "Green"
aaaarrcolors(2) = "Red"
aaaarrcolors(3) = "White"
aaaarrcolors(4) = "Black"
aaaarrcolors(5) = "Yellow"
arrubound = ubound(arrcolors)
aaamsgbox arrubound
aaaaaaFor i = 0 to arrubound
aaaaaaaaamsgbox arrcolors(i)
aaaaaaNext
aaaaaaFor each element in arrcolors
aaaaaaaaamsgbox element
aaaaaaNext
Monday, April 26, 2010
What is Array in VB scripting
First of all let us understand what is an array in VB Scripting. How are arrays used in VB Scripting. What is the purpose of array in VB Script. Is there any difference between an array and a variable since both store values? What does an array do and how does an array store values.
Array is a matrix of data. The difference between a variable and an array is that a variable holds a single value while an array holds multiple values. Array can be Static and Dynamic.
An array is said to be static if the upper limit of the array is known or defined. If the upper limit is not defined and the value is fetched from some other place or a user input it is known as Dynamic array.
Arrays should always be declared with a Dim Statement. In VB script a Dynamic array is classified as Homogenous and Heterogeneous. A Homogenous array hold the same type of data while an heterogeneous array is a mix of different data types.
Generally an array in VB Script can be of 60 dimensions.
Syntax of a Single Dimensional Array
Dim [Array name] (index)
It is to be noted that in an array the index begins with zero.
Syntax of a two dimensional array
Dim [Array name] (column id, row id)
Example of a two dimensional array
Dim arrphonelist (2,3)
Arrphonelist is the name of the array while 2 is the column id and is also known as 1st dimension and 3 is the row id and is also known as 2nd dimension.
To get the row count of an array we write like this
Row_count = ubound(arrphonelist, 2)
For column count it is like this even though we predefine the number of rows as a best practice but still to have an idea we write like this
column_count = ubound(arrphonelist, 1)
In an array always the columns are fixed and only rows are manipulated.
IN Built VB Script Functions
As far as VB Scripting for QTP is concerned we will look at the four types of In Built Functions of VB scripting since we use them very often in QTP while writing scripts. The four inbuilt functions are
1. Data & Time Function
2. String Function
3. Conversion function
4. Array Function
Date & time Function
CDate: Converts a valid date and time expression to the variant of subtype DateDate: Returns the current system date
DateAdd: Returns a date to which a specified time interval has been added
DateDiff : Returns the number of intervals between two dates
Example of DateDiff is
Msgbox datediff("d", #mm/dd/yyyy#, Now)
Here d refers Day. This will print the difference in no of days.
String Function
With a String function we can scan the entire string and also get a count of the no of characters in the string. If needed we can use the Left and Right method to get a particular no of characters either from the left or right side of the string. You can also replace the string with a new value.
Str = “This is Friday”
Str = Right (str, 20)
Str = Left (str, 8)
The Left and Right Methods scan the string from Left/Right and prints the specified no of characters.
Str = “Hello World”
Arr = split(str, "o")
Msgbox arr(0)
Msgbox arr(1)
Msgbox arr(2)
In the first message box it will print 'Hell', In the Second Message box it will print 'W', in the third message box it will print 'rld'.
If you want to check whether a text file is there in a Folder then you need to use the split method to get the text file. After getting the folder using Get Folder and pointing to the files in the folder we need to write these lines of code in the For Next Loop.
For each f in fil
str = f.name
arr = split(str, ".")
If arr(1) = "txt" then
var = var&Vbnewline&f.name
End If
Next
Please look at the complete script for printing all the text files in a folder at
How to display all the Text Files in a Folder
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. 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.
Method 1
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible=True
objExcel.workbooks.Add()
Const ForReading =1
Set FSO = CreateObject("Scripting.FileSystemObject")
Set file = FSO.OpenTextFile("F:\TestFolder\Text1.txt", 1)
x=1
Do Until File.AtEndOfStream
Line = File.ReadLine
objExcel.Cells(x,1) = Line
x=x+1
Loop
objFile.Close
Method 2
'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.FileSystemObject")
Set xlapp = CreateObject("Excel.Application")
'Create a text files using CreateTextFile method
Set fil = Fso.CreateTextFile("F:\TestFolder\Text1.txt")
Set wbook = xlapp.Workbooks.Add
set wsheet = xlapp.worksheets(1)
'Write few lines into the first text file
For i = 1 to 100
fil.WriteLine("This is Line "&i)
Next
Set fil = nothing
'Open first text file in read mode and write in excel sheet
Set fil1 = fso.OpenTextFile("F:\TestFolder\Text1.txt",1, False)
X=1
Do Until fil1.AtEndOfStream
strLine = fil1.ReadLine
xlapp.Cells(x,1) = strLine
X=x+1
Loop
wbook.SaveAs "F:\TestFolder\Test.xls"
set wbook=nothing
xlapp.quit
set wsheet = nothing
Set fil = nothing
Set fil1=Nothing
Set fil2 = nothing
Sunday, April 25, 2010
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.
'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.GetFolder("F:\TestFolder")
'Step 3: Return all the files collection from the specified folder
Set fil = Fol.Files
'Print only the text file names from the specified folder
For each f in fil
str = f.name
arr = split(str, ".")
If arr(1) = "txt" then
var = var&Vbnewline&f.name
End If
Next
msgbox "The Text Files in the Folder "TestFolder" are: "&vbnewline&var
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.
'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.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.name&", "
Next
Msgbox The files in the Folder YouTube Downloader are " &Vbnewline&str
Thursday, April 22, 2010
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.
Let us look at some of the common methods used to deal with Excel Library.
Workbooks Method is used to point to a work book.
Worksheet method is used to point to a worksheet.
Before creating a Workbook or worksheet we need to create an Object to interact with Excel Library.
The syntax to create an object is
Set [Object] = CreateObject("Excel.Application")
Set xlapp = CreateObject("Excel.Application")
To Create a new workbook we need to use this syntax. The syntax to add a workbook is
Set [Variable] = Object.Workbooks.Add
Set wbook = xlapp.Workbooks.Add
To Open an existing workbook we need to use this syntax. The syntax to open an existing workbook is
Set [Variable] = Object.Workbooks.Open ()
Set wbook = xlapp.Workbooks.Open("F:\TestFolder ")
Set wbook = xlapp.Workbooks.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.worksheets(id)
Set wsheet = xlapp.worksheets(1)
Set wsheet = xlapp.worksheets("Testing")
Here id can be the sheet id and the index begin with 1. You can also give a string for the id but should be enclosed in " ".
To save a new workbook in a destination we use this syntax
Variable.SaveAs ()
wbook.SaveAs(("F:\TestFolder\Test.xls")
wbook.SaveAs(("F:\TestFolder\Test.xls")
Every time a workbook is created or opened it should be closed and to close the workbook we need a Close Method. To close a Work book the syntax is
Variable.Close
wbook.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. The syntax is
Object.Quit
Xlapp.Quit
As soon as the application is quit it is required to clear the variables so that it does not interfere with other scripts. It is important that the worksheet, workbook, excel application variables should be cleared. To clear the variable used from the memory we use the Nothing Method. 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.cells(rows,columns)
wsheet.cells(1,1)
Each Cell is identified with Row and Column as (Row, Column)
Check this script to understand how these methods are used.
VB Script using Excel Library Methods and Properties
VB Script using Excel Library Methods and Properties
Write a Script to create a workbook and create a worksheet and add information in the cells in VB script using Excel Library.
The Script to create a workbook and worksheets with cells is given below.
'Create an Object variable to interact with Excel Library
Set xlapp = CreateObject("Excel.Application")
'Create New Excel Workbook using the xlapp object
Set wbook = xlapp.workbooks.Add
'Create a pointer to the first sheet in the workbook
Set wsheet = xlapp.worksheets(1)
'Here we are adding the data in first column and color in second column
For i = 1 to 56
wsheet.cells(i,1).value = "The code of this color is: "&i
wsheet.cells(i,1).font.Name = "Verdana"
wsheet.cells(i,1).font.Size = 14
wsheet.cells(i,1).font.bold=TRUE
wsheet.cells(i,1).font.colorindex=i
wsheet.cells(i,2).interior.colorindex=i
Next
wbook.SaveAs "F:\Textexcel.xls"
wbook.Close
xlapp.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. 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 black color and in bold and in the cell (1,2) you will find the cell filled with black color and like wise till row number 56.
You can manipulate the cells or using the wsheet.cells(rows,columns) syntax.
Wednesday, April 21, 2010
Creating and Managing Folders using VB Script
We can create Folders in VB Script interacting with File System Object. So using the script we can create folder, manipulate with folders etc through VB Scripting.
Create Folder Method creates a folder in the location specified. If a folder already exists with the same name an error occurs. The CreateFolder method always returns a Folder object if it is not there. The syntax of the CreateFolder method is
object.CreateFolder(foldername)
Example 1: Write a script to print all the file names from a folder.
'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.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.name&", "
Next
Msgbox "The file name is: "&str
If we look in the above script we look at this line str = str&" "&f.name&", "
Let me explain what actually happens. In order to print all the file names in a single message box we need to initialize a string in the loop and assign the string with str and concatenate with space and f.name (file name) and a comma so that each file will be displayed separated by a comma. What happens is that the str will start storing all the file names until the loop is terminated and this string is used in the message box to print the desired output.
For each statement is used to point to each file till it reaches the end of the file collection. Here f variable is used to point to each file in the collection.
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.
'Script to create two text files,
'Write few lines into the first text file.
'Copy all the odd lines from the
'first text file to the second text file
'Create an object variable to interact with the File System Object
Set Fso = CreateObject("Scripting.FileSystemObject")
'Create Two text files using CreateTextFile method
Set fil = Fso.CreateTextFile("F:\Text1.txt")
Fso.CreateTextFile("F:\Text2.txt")
'Write few lines into the first text file
For i = 1 to 100
fil.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.OpenTextFile("F:\Text1.txt",1, False)
Set fil2 = fso.OpenTextFile("F:\Text2.txt",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.AtEndOfStream
Line_number = fil1.line
If Line_number MOD 2 <> 0 Then
fil2.WriteLine(fil1.ReadLine)
Else
fil1.SkipLine
End If
Loop
Set fil = nothing
Set fil1=Nothing
Set fil2 = nothing
Write and Writeline Method in VB script
We can use VB script to create a text file and write some lines in the text file using the File System Object.
Write Method
Write Method writes a line and the cursor is placed at the end of the line and the next line will be continued from the end of the first line. Write Method writes a specified string to a Text Stream file.
The Syntax of the Write Method is
object.Write(string)
Example: To write a script to print 10 lines.
'Create a text file and write some lines into it
'Step 1: Create and object variable to interact with the File system object
set fso=CreateObject("Scripting.filesystemobject")
'Step 2: Create the test file.
set fil = fso.CreateTextFile("F:\Test1.txt")
'Step 3: Writing the lines into the file using For Loop
For i = 1 to 10
fil.Write ("This is line "&i)
Next
When the script is executed it displays the 10 lines like this.
This is line 1This is line 2This is line 3This is line 4This is line 5This is line 6This is line 7This is line 8This is line 9This is line 10
WriteLine Method
WriteLine method write statements in different lines. The cursor is placed at the next Line or New Line. Writes a specified string and newline character to a TextStream file.
The syntax of the WriteLine method is
object.WriteLine([string])
Example: To write a script to print 10 lines in different rows.
'Create a text file and write some lines into it
'Step 1: Create and object variable to interact with the File system object
set fso=CreateObject("Scripting.filesystemobject")
'Step 2: Create the test file.
set fil = fso.CreateTextFile("F:\Test1.txt")
'Step 3: Writing the lines into the file using For Loop
For i = 1 to 10
fil.WriteLine ("This is line "&i)
Next
When this script is executed the output is displayed like this
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
This is line 10
Tuesday, April 20, 2010
Calling FileSystemObject from VB Script
Previous | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | Next |
How to call from FileSystemObject Library
For us to write VB scripts for QTP we generally interact with FileSystemObject and Excel Objects. There is a process in calling a FileSystemObject Object and use it in the VB script to get the desired output.
In order to call from FileSystemObject (FSO) Library we first need to create and Object Variable.
An Object Variable is a Variant with sub type which holds an Object and should be prefixed with a Key word called "SET". To interact with different libraries we need to create Objects and these Objects are used along with different Methods to perform different operations.
Let us look at some examples to create Object to use from different Libraries.
Set Fso = CreateObject("Scripting.FileSystemObject")
Here we are creating an object to call a method from the File System Object Library
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 Internet Explorer Library
Set QtpApp = CreateObject("QuickTest.Application")
Here we are creating an object to call a method from the Quick Test Library
Set doc = CreateObject("Word.Application")
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 Outlook Library
All the above variables are used as a standard convention to understand as to what the object is doing.
Please look at the following scripts where File System Object is used in VB Script for various purposes.
1. How to Create a Text File using VB Script? Click Here for the Code
2. How to create multiple Text Files? Click Here for the Code
3. How to create a Folder using VB script? Click Here for the Code
4. How to display File Properties in VB script? Click Here for the Code
Previous | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | Next |
Objects and Classes
Previous | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | Next |
What is an Object?
Let’s spend some time in understanding what is a class, object. Class is a collection of objects which has properties and methods.
Classes are of two types.
1. Standard Class: which are loaded in the Library or which are predefined and we just need to call them and use them. We cannot make any changes to them.
Let us see what an Object contains.
1. Objects have properties and Methods.
2. An object is an instance of a Class.
3. Properties define characteristics of an Object.
4. Methods are the actions performed by the Objects.
Let’s take an example of a Class Room. Let’s say that we have two classes named Male and Female. All the individuals are Objects and they fall into either of the class. Now each of this Object (individual) has some properties and Methods.
Properties for the above object can be Name, Date of Birth, Height, Weight, Color and some properties are Read Only which cannot be changed while some others can be changed. For Example: Date of Birth cannot be changed while height and weight can be changed or even the name.
Methods for the above Object can be Sleeping, Eating, working, playing etc which are actions performed by the Object.
Previous | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | Next |
File System Object
Previous | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | Next |
What is a File System Object
File System Object or FileSystemObject helps us to deal with Files, Folders and Drives using VB Script. We generate Scripts using VB to interact with them.
We can interact with FileSystemObject using VB Script and can perform different kinds of operations as we desire. Using FileSystemObject in VB Script we can create a File, Folder. You can also write data or information in a File. Yo
u can also Delete a File, Folders or data in VB using FileSystemObject.
It is possible to get different kind of information on Files, Folders and Drives with the help of FileSystemObject using VB Script.
FileSystemObject is a separate library and not included in VB Script Library. VB Script needs to call the FileSystemObject Library. Like wise VB Script can interact with different libraries and call them using different objects.
VB Script can talk to any of the libraries like FileSystemObject, Word, Excel etc. This is referred to as Component Object Model or COM
Look at the Component Object Model or COM figure.
Previous | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | Next |
Display of File Properties in VB Scrip using FileSystemObject
Back To File System Object Page
How to display File Properties in VB script?
'Create a Folder using FSO or FileSystemObject
Back To File System Object Page
How to display File Properties in VB script?
Using the File System Object method CreateFile we create a File and Using the GetFile Method we get the newly created File. Then we use the name, size etc methods to get the properties of the file.
'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.FileSystemObject")
'Step 2: use the CreateTextFile to Create a Text File
Fso.CreateTextFile("F:\Text.txt")
'Step 3: Use the GetFile Method to get the information of the file and set it to a Object Variable
Set F=Fso.GetFile("F:\Text.txt")
'Step 4: Print the Properties of the File using various
MsgBox "The File name is: "&f.name&"" &vbnewline& "The File Size is: "&f.size&""&vbnewline& "The File Creation Date is: "&f.DateCreated&""&vbnewline& "The File Last Modified on: "&f.DateLastModified
Back To File System Object Page
Creating a Folder in VB Script using FileSystemObject
Back To File System Object Page
How to create a Folder using VB script?
'Create a Folder using FSO or FileSystemObject
Back To File System Object Page
How to create a Folder using VB script?
Using the File System Object method CreateFolder we create a Folder and Using the GetFolder Method we get the newly created Folder.
'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.FileSystemObject")
'Step 2; Use the CreateFolder method along with the object to create a Folder at desired location
Fso.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.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.name
Back To File System Object Page
Creating multiple Text files in VB Script using FileSystemObject
Back To File System Object Page
How to create multiple Text Files?
Example 1: Assuming we know how many text files to create.
'Create a Text File using FSO or FileSystemObject
Example 2: Asking the user for input to print that many number of files.
Rewrite the code by just adding one line with InputBox function.
'Create a Text File using FSO or FileSystemObject
Back To File System Object Page
How to create multiple Text Files?
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. Using a InputBox we can also ask the user how many text files to be created.
Example 1: Assuming we know how many text files to create.
'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.FileSystemObject")
'Step 2: Use For Loop to run the script for 100 times.
For I = 1 to 5
Fso.CreateTextFile("F:\Test"&i&".txt")
var = "" &var&", Test" &i
Next
Msgbox" The Text Files Created are "&Var
Example 2: Asking the user for input to print that many number of files.
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.FileSystemObject")
'Step 2: Use For Loop to run the script for 100 times.
n=CINT(InputBox("Enter how many files to be created"))
For I = 1 to n
Fso.CreateTextFile("F:\Test"&i&".txt")
var = "" &var&", Test" &i
Next
Msgbox" The Text Files Created are "&Var
Back To File System Object Page
Creating a Text File in VB Script using FileSystemObject
Back To File System Object Page
'Create a Text File using FSO or 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.
'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.FileSystemObject")
'Step 2: Use the CreateTextFile method along with the object to create a text file at desired location.
Fso.CreateTextFile("F:\Test.txt")
'Step 3: Use the GetFile method to get the newly created file and store in a variable called s.
Set s = fso.GetFile("F:\Test.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.name
Back To File System Object Page
Friday, April 16, 2010
Assignment Answer on Functions.
Back to the Previous Page
The code looks like this
Here you are asking the user for the choice to perform the operation.
n=Inputbox("Enter your choice"&vbnewline&" "&vbnewline&"1 - Addition"&vbnewline&
Here you are selecting the case based on the user input and appropriately calling the required function.
Select Case n
Here you are actually defining the functions for different operations to be performed.
For Addition of two Numbers
Function addfunc(byval x, byval y)
For Subtraction of two Numbers
Function minusfunc(byval x, byval y)
For Multiplication of two Numbers
Function multiply(byval x, byval y)
For finding quotient of two Numbers
Function quotient (byval x, byval y)
For displaying the Fibonacci Series of a given Number
Function Fibonacci (byval var)
For displaying the Odd Numbers of a given Number
Function oddfunc(byval var)
For displaying the Prime numbers of a given Number
Function prime(byval var)
For converting from and to Centigrade or Fahrenheit of a given Number
Function conversion(byval cen, byval fah)
Back to the Previous Page
Write a script in VB to Convert all the previous written scripts like Fibonacci series in VB Script, Prime number Generation in VB Script, Odd number generation in VB Script, conversion from centigrade to Fahrenheit in VB Script, Addition in VB Script, Multiplication in VB Script etc using functions in VB Script.
In order to write this script first we need to use a inputbox to ask the user the choice to perform a certain function. 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.After the Select Case Write down all the Functions for different operations.
The code looks like this
Here you are asking the user for the choice to perform the operation.
n=Inputbox("Enter your choice"&vbnewline&" "&vbnewline&"1 - Addition"&vbnewline&
"2 - Subtraction"&vbnewline&"3 - Multiplication"&vbnewline&"4 - Quotient"&vbnewline&
"5 - Fibonacci Series"&vbnewline&"6 - Odd Numbers"&vbnewline&"7 - Prime Numbers"&vbnewline&"8 - Degree Conversion")
Here you are selecting the case based on the user input and appropriately calling the required function.
Select Case n
Case 1
aaaaddfunc x,y
Case 2
aaaminusfunc x,y
Case 3
aaamultiply x,y
Case 4
aaaquotient x,y
Case 5
aaaFibonacci var
Case 6
aaaoddfunc var
Case 7
aaaprime var
case 8
aaaconversion cen, fah
Case Else
aaamsgbox "invalid entry"
End Select
Here you are actually defining the functions for different operations to be performed.
For Addition of two Numbers
Function addfunc(byval 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, 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: "&x-y
End Function
For Multiplication of two Numbers
Function multiply(byval x, 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, 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& ", " &f2
aaaaaado while f3 < n
aaaaaaaaavar =" var&", "&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
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& ", "
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, 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.55555555556 + 32& " Fahrenhite"
aaaaaCase 2
aaaaaaafah=inputbox("Enter the value to be converted")
aaaaaaamsgbox "The converted value of " &fah& " Fahrenheit is " &(fah-32) *0.55555555556 & " Centigrade"
aaaaaCase Else
aaaaaaamsgbox "Invalid entry for Conversion"
aaaEnd Select
End Function
Back to the Previous Page
VB Scripting - Passing an argument by reference- byref
Previous | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | Next |
The scope of a variable can be changed in VB Script using parameters associated with the arguments. Passing an argument by reference using byref in VB will destroy the previous assigned value to the variable.
An argument is always defined by parameters either by reference or by value depending upon how it is declared in the function or procedure.
If a value is passed into a function as an argument by reference then the value of that variable is passed to the function. If the value of that variable is changed inside the function it would impact the original value. In other words the original value is replaced by this value.
Let’s take an example and try to understand what happens when a value to an argument is passed by reference.
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.
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.
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. 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
Int1=CINT(Inputbox("Enter value one"))
Int2=CINT(Inputbox("Enter value two"))
Function multiply (byval Int1, byval Int2, byref prod)
aaaProd = Int1*Int2
End Function
Multiply Int1, Int2, x
aaamsgbox"The product of Value one and two is: "&x
Assignment: Convert all the previous written scripts like Fibonacci series, Prime number Generation, Odd number generation, conversion from centigrade to Fahrenheit, Addition, Multiplication etc using functions in VB Script.
Note: Use Inputbox to as the user choice to perform what operation is required. Create Function calls and then Use Select Case to select the particular function based on the user choice.
For Answer Please Click Here
Previous | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | Next |
VB Scripting - Passing an argument by Value using byval
Previous | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | Next |
The scope of a variable can be changed in VB Script using parameters associated with the arguments. Passing an argument by value using byval in VB creates a copy of the variable.
An argument is always defined by parameters either by reference or by value depending upon how it is declared in the function or procedure.
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. 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. Lets look at one example to understand what it means by byval or passing an argument by value.
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.
First the x is assigned as 20 and the msgbox in the second line prints 20.
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.
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 20 because the local variable x value is overwritten with the global value and prints 20.
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.
Int1=CINT(Inputbox("Enter value one"))
Int2=CINT(Inputbox("Enter value two"))
Function multiply(byval Int1, byval Int2)
aaamultiply = Int1*Int2
End Function
aaamsgbox "The product of Value one and two is: "&multiply(Int1, Int2)
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. The modified code will be like this
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,Int2)
aaamsgbox"The product of Value one and two is: "&x
Previous | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | Next |
VB Scripting - Scope of a Variable
Previous | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | Next |
Defining the Scope of a Variable in VB Script
Variables in VB Script is used for assigning values and using them for different operations. The scope of Variable in VB Script can be classified as Local Variable and Global Variable.
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. The scope of a variable determines where it should be used in the script. The scope of a variable depends on its declaration in the script. The scope of a variable is of two types.
1. Procedure Level Variable.
2. Script Level Variable.
Procedure Level Variables are also called as Local Variables because they can only be used in the Procedure or Function. 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.
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 based on the passby values. These Script Level variables are always declared out side the procedures.
Previous | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | Next |
VB Scripting - Function Call
Previous | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | Next |
What is a Function Call in VB Script?
In continuation with the previous discussion of Functions and Procedures in VB Script, 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. The whole Function what we write is called a 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. 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.
This is a general rule that the Function Definition should happen first and then the Function Call. 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. A function can have zero or more arguments.
Function call can happen any where in the script. 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, ease of understanding.
VB Script searches first the function and then goes and Function Definition and executes the function.
Previous | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | Next |