Anda di halaman 1dari 51

VB Script Variables Definition 1): Variable is a named memory location for storing program information Definition 2): A variable

is a convenient placeholder that refers to a computer memory location where we can store program information that may change during the time our script is running. Purpose of Variable: a) Comparing values Example: b) Holding Program Result Example: Cost=Tickets*Price c) Passing parameters d) To store data that returned by functions Example: myDate=Now It returns current data & time e) To hold data Example: myName=ranga Declaring Variables We declare variables explicitly in our script using the Dim statement, the Public statement, and the Private statement. For example: Dim city Dim x We declare multiple variables by separating each variable name with a comma. For Example:

Dim x, y, city, ranga We can also declare a variable implicitly by simply using its name in our script. That is not generally a good practice because we could misspell the variable name in one or more places, causing unexpected results when our script is run. For that reason, the Option Explicit statement is available to require explicit declaration of all variables. The Option Explicit statement should be the first statement in our script. Option Explicit Statement Forces explicit declaration of all variables in a script. Option Explicit ' Force explicit variable declaration. Dim MyVar ' Declare variable. MyInt = 10 ' Undeclared variable generates error. MyVar = 10 ' Declared variable does not generate error. Naming Restrictions for Variables Variable names follow the standard rules for naming anything in VBScript. A variable name: a) Must begin with an alphabetic character. Dim abc 'Right Dim 9ab 'Wrong Dim ab9 'Right b) Cannot contain an embedded period. Dim abc 'Right Dim ab.c 'worng Dim ab-c 'wrong Dim ab c 'wrong Dim ab_c 'Right c) Must not exceed 255 characters. d) Must be unique in the scope in which it is declared. Scope of Variables A variable's scope is determined by where we declare it. When we declare a variable within a procedure, only code within that procedure can access or change the value of that variable. If we declare a variable outside a procedure, we make it recognizable to all the procedures in our script. This is a script-level variable, and it has script-level scope. Example: Dim x,y,z x=10

y=20 z=x+y msgbox z 'Returns 30 Function res Dim a,b,c a=30 b=40 c=a+b+y msgbox c ' Returns 90 End Function Call res Life Time of Variables The lifetime of a variable depends on how long it exists. The lifetime of a script-level variable extends from the time it is declared until the time the script is finished running. At procedure level, a variable exists only as long as you are in the procedure. Assigning Values to Variables Values are assigned to variables creating an expression as follows: The variable is on the left side of the expression and the value you want to assign to the variable is on the right. For example: A = 200 City = Hyderabad X=100: Y=200 Scalar Variables and Array Variables A variable containing a single value is a scalar variable. A variable containing a series of values, is called an array variable. Array variables and scalar variables are declared in the same way, except that the declaration of an array variable uses parentheses () following the variable name. Example: Dim A(3) Although the number shown in the parentheses is 3, all arrays in VBScript are zero-based, so this array actually contains 4 elements. We assign data to each of the elements of the array using an index into the array.

Beginning at zero and ending at 4, data can be assigned to the elements of an array as follows: A(0) = 256 A(1) = 324 A(2) = 100 A(3) = 55 Similarly, the data can be retrieved from any element using an index into the particular array element you want. For example: SomeVariable = A(4) Arrays aren't limited to a single dimension. We can have as many as 60 dimensions, although most people can't comprehend more than three or four dimensions. In the following example, the MyTable variable is a two-dimensional array consisting of 6 rows and 11 columns: Dim MyTable(5, 10) In a two-dimensional array, the first number is always the number of rows; the second number is the number of columns. Dynamic Arrays We can also declare an array whose size changes during the time our script is running. This is called a dynamic array. The array is initially declared within a procedure using either the Dim statement or using the ReDim statement. However, for a dynamic array, no size or number of dimensions is placed inside the parentheses. For example: Dim MyArray() ReDim AnotherArray() To use a dynamic array, you must subsequently use ReDim to determine the number of dimensions and the size of each dimension. In the following example, ReDim sets the initial size of the dynamic array to 25. A subsequent ReDim statement resizes the array to 30, but uses the Preserve keyword to preserve the contents of the array as the resizing takes place. ReDim MyArray(25) ReDim Preserve MyArray(30)

There is no limit to the number of times we can resize a dynamic array, although if we make an array smaller, we lose the data in the elimina VB Script General Examples 1) Write a program for finding out whether the given year is a leap year or not? Dim xyear xyear=inputbox ("Enter Year") If xyear mod 4=0 Then msgbox "This is a Leap year" Else msgbox "This is NOT" End If 2) Write a program for finding out whether the given number is, Even number or Odd number? Dim num num=inputbox ("Enter a number") If num mod 2=0 Then msgbox "This is a Even Number" Else msgbox "This is a Odd Number" End If 3) Read two numbers and display the sum? Dim num1,num2, sum num1=inputbox ("Enter num1") num2=inputbox ("Enter num2") sum= Cdbl (num1) + Cdbl (num2) 'if we want add two strings conversion require msgbox ("Sum is " &sum) 4) Read P,T,R values and Calculate the Simple Interest? Dim p,t, r, si p=inputbox ("Enter Principle") t=inputbox ("Enter Time") r=inputbox ("Enter Rate of Interest") si= (p*t*r)/100 ' p= principle amount, t=time in years, r= rate of interest msgbox ("Simple Interest is " &si) 5) Read Four digit number, calculate & display the sum of the number or display Error message if the number is not a four digit number? Dim num, sum num=inputbox ("Enter a Four digit number") If Len(num) = 4 Then sum=0 sum=sum+num mod 10

num=num/10 num= left (num, 3) sum=sum+num mod 10 num=num/10 num= left (num, 2) sum=sum+num mod 10 num=num/10 num= left (num, 1) sum=sum+num mod 10 msgbox ("Sum is " &sum) else msgbox "Number, you entered is not a 4 digit number" End If 6) Read any Four-digit number and display the number in reverse order? Dim num,rev num= inputbox("Enter a number") If len(num)=4 Then rev=rev*10 + num mod 10 num=num/10 num= left(num,3) rev=rev*10 + num mod 10 num=num/10 num= left(num,2) rev=rev*10 + num mod 10 num=num/10 num= left(num,1) rev=rev*10 + num mod 10 msgbox "Reverse Order of the number is "&rev Else msgbox "Number, you entered is not a 4 digit number" End If 7) Read 4 subjects marks; calculate the Total marks and grade? a) If average marks Greater than or equal to 75, grade is Distinction b) If average marks Greater than or equal to 60 and less than 75 , then grade is First c) If average marks Greater than or equal to 50 and less than 60 , then grade is Second d) If average marks Greater than or equal to 40 and less than 50 , then grade is Third e) Minimum marks 35 for any subject, otherwise 'no grade fail') Dim e,m,p,c, tot e=inputbox ("Enter english Marks") m=inputbox ("Enter maths Marks") p=inputbox ("Enter physics Marks") c=inputbox ("Enter chemistry Marks") tot= cdbl(e) + cdbl(m) + cdbl(p) + cdbl(c) msgbox tot

If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=300 Then msgbox "Grade is Distinction" else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=240 and tot<300 Then msgbox "Grade is First" else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=200 and tot<240 Then msgbox "Grade is Second" else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=160 and tot<200 Then msgbox "Grade is Third" else msgbox "No Grade, Fail" End If End If End If End If 8) Display Odd numbers up to n? Dim num,n n=Inputbox ("Enter a Vaule") For num= 1 to n step 2 msgbox num Next 9) Display Even numbers up to n? Dim num,n n=Inputbox ("Enter a Vaule") For num= 2 to n step 2 msgbox num Next 10) display natural numbers up to n and write in a text file? Dim num, n, fso, myfile n= inputbox ("Enter any Value") num=1 For num= 1 to n step 1 Set fso= createobject ("scripting.filesystemobject") set myfile=fso.opentextfile ("E:\ranga.txt", 8, true) myfile.writeline num myfile.close Next 11) Display Natural numbers in reverse order up to n? Dim num,n

n=Inputbox ("Enter a Vaule") For num=n to 1 step -1 msgbox num Next 12) Display Natural numbers sum up to n? (Using For...Next Loop) Dim num, n, sum n= inputbox ("Enter a Value") sum=0 For num= 1 to n step 1 sum= sum+num Next msgbox sum 13) Display Natural numbers sum up to n? (using While...Wend Loop) Dim num, n, sum n= inputbox ("Enter a Value") While num <=cdbl (n) sum= sum+num num=num+1 Wend msgbox sum 14) Display Natural numbers sum up to n? (Using Do...Until...Loop) Dim num, n, sum n= inputbox ("Enter a Value") sum=0 num=1 Do sum= sum+num num=num+1 Loop Until num =cdbl (n+1) msgbox sum 15) Write a Function for Natural Numbers sum up to n? Function NNumCou (n) Dim num, sum sum=0 For num= 1 to n step 1 sum= sum+num Next msgbox sum End Function 16) Verify weather the entered 10 digit value is a numeric value or not?

Dim a,x,y,z,num num=Inputbox ("Enter a Phone Number") d1= left (num,1) d10=Right (num,1) d2=mid (num, 2, len (1)) d3=mid (num, 3, len (1)) d4=mid (num, 4, len (1)) d5=mid (num, 5, len (1)) d6=mid (num, 6, len (1)) d7=mid (num, 7, len (1)) d8=mid (num, 8, len (1)) d9=mid (num, 9, len (1)) If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isnumeric (d10) = "True" Then msgbox "It is a Numeric Value" else Msgbox "It is NOT Numeric" End If 17) Verify weather the entered value is a 10 digit value or not and Numeric value or not? (Using multiple if conditions) Dim a,x,y,z,num num=Inputbox ("Enter a Phone Number") d1= left (num,1) d10=Right (num,1) d2=mid (num, 2, len (1)) d3=mid (num, 3, len (1)) d4=mid (num, 4, len (1)) d5=mid (num, 5, len (1)) d6=mid (num, 6, len (1)) d7=mid (num, 7, len (1)) d8=mid (num, 8, len (1)) d9=mid (num, 9, len (1)) If len (num) =10 Then If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isnumeric (d10) = "True" Then msgbox "It is a Numeric Value" End If End If If len (num) <> 10 Then

Msgbox "It is NOT valid Number " End If 18) Generate interest for 1 to 5 years (for 1 year -7%, 2 years -8%, 3 years-9%, 4 years-10%, 5 years -11%) Dim amount, duration, intr amount=inputbox("enter amount") If amount<10000 Then msgbox "low amount" else For duration=1 to 5 If duration=1 Then intr=amount*7/100 msgbox "1 year intrest is: " &intr else if duration=2 Then intr=amount*8/100 msgbox "2 years intrest is: " &intr else if duration=3 Then intr=amount*9/100 msgbox "3 years intrest is: "&intr else if duration=4 Then intr=amount*10/100 msgbox "4 years intrest is: "&intr else if duration=5 Then intr=amount*11/100 msgbox "5 years intrest is: "&intr else msgbox "invalid data" End If End If End If End If End If Next End If Input and Out Put Operations InputBox Function Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns the contents of the text box.

Example: Dim Input Input = InputBox("Enter your name") MsgBox ("You entered: " & Input) MsgBox Function Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked. Example: Dim MyVar MyVar = MsgBox ("Hello World!", 65, "MsgBox Example") MyVar contains either 1 or 2, depending on which button is clicked. VB Script Constants A constant is a meaningful name that takes the place of a number or string and never changes. Creating Constants We create user-defined constants in VBScript using the Const statement. Using the Const statement, we can create string or numeric constants with meaningful names and assign them literal values. Const statement Declares constants for use in place of literal values. Example: Const MyString = "This is my string." Const MyAge = 49 Const CutoffDate = #6-1-97#

Note that String literal is enclosed in quotation marks (" "). Represent Date literals and time literals by enclosing them in number signs (#).

We declare multiple constants by separating each constant name and value with a comma. For example: Const price= 100, city= Hyderabad, x= 27 Flow Control (Conditional Statements) We can control the flow of our script with conditional statements and looping statements. Using conditional statements, we can write VBScript code that makes decisions and repeats actions. The following conditional statements are available in VBScript: 1) IfThenElse Statement 2) Select Case Statement Making Decisions Using If...Then...Else The If...Then...Else statement is used to evaluate whether a condition is True or False and, depending on the result, to specify one or more statements to run. Usually the condition is an expression that uses a comparison operator to compare one value or variable with another. If...Then...Else statements can be nested to as many levels as you need. 1) Running a Statement if a Condition is True (single statement) To run only one statement when a condition is True, use the single-line syntax for the If...Then...Else statement. Dim myDate myDate = #2/13/98# If myDate < Now Then myDate = Now 2) Running Statements if a Condition is True (multiple statements) To run more than one line of code, we must use the multiple-line (or block) syntax. This syntax includes the End If statement. Dim x x= 20 If x>10 Then msgbox "x value is: "&x msgbox "Bye Bye" End If

3) Running Certain Statements if a Condition is True and Running Others if a Condition is False We can use an If...Then...Else statement to define two blocks of executable statements: one block to run if the condition is True, the other block to run if the condition is False. Example: Dim x x= Inputbox (" Enter a value") If x>100 Then Msgbox "Hello G.C.Reddy" Msgbox "X is a Big Number" Msgbox "X value is: "&X Else Msgbox "GCR" Msgbox "X is a Small Number" Msgbox "X value is: "&X End If 4) Deciding Between Several Alternatives A variation on the If...Then...Else statement allows us to choose from several alternatives. Adding ElseIf clauses expands the functionality of the If...Then...Else statement so we can control program flow based on different possibilities. Example: Dim x x= Inputbox (" Enter a value") If x>0 and x<=100 Then Msgbox "Hello G.C.Reddy" Msgbox "X is a Small Number" Msgbox "X value is "&x Else IF x>100 and x<=500 Then Msgbox "Hello GCR" Msgbox "X is a Medium Number" Else IF x>500 and x<=1000 Then Msgbox "Hello Chandra Mohan Reddy" Msgbox "X is a Large Number" Else Msgbox "Hello Sir" Msgbox "X is a Grand Number"

End If End If End If 5) Executing a certain block of statements when two / more conditions are True (Nested If...) Example: Dim State, Region State=Inputbox ("Enter a State") Region=Inputbox ("Enter a Region") If state= "AP" Then If Region= "Telangana" Then msgbox "Hello G.C.Reddy" msgbox "Dist count is 10" Else if Region= "Rayalasema" Then msgbox "Hello GCR" msgbox "Dist count is 4" Else If Region= "Costal" Then msgbox "Hello Chandra mohan Reddy" msgbox "Dist count is 9" End If End If End If End If Making Decisions with Select Case The Select Case structure provides an alternative to If...Then...ElseIf for selectively executing one block of statements from among multiple blocks of statements. A Select Case statement provides capability similar to the If...Then...Else statement, but it makes code more efficient and readable. Example:

Option explicit Dim x,y, Operation, Result x= Inputbox (" Enter x value") y= Inputbox ("Enter y value") Operation= Inputbox ("Enter an Operation") Select Case Operation

Case "add" Result= cdbl (x)+cdbl (y) Msgbox "Hello G.C.Reddy" Msgbox "Addition of x,y values is "&Result Case "sub" Result= x-y Msgbox "Hello G.C.Reddy" Msgbox "Substraction of x,y values is "&Result Case "mul" Result= x*y Msgbox "Hello G.C.Reddy" Msgbox "Multiplication of x,y values is "&Result Case "div" Result= x/y Msgbox "Hello G.C.Reddy" Msgbox "Division of x,y values is "&Result Case "mod" Result= x mod y Msgbox "Hello G.C.Reddy" Msgbox "Mod of x,y values is "&Result Case "expo" Result= x^y Msgbox "Hello G.C.Reddy" Msgbox"Exponentation of x,y values is "&Result Case Else Msgbox "Hello G.C.Reddy" msgbox "Wrong Operation" End Select Looping Through Code Flow Control (Loop Statements) o Looping allows us to run a group of statements repeatedly. o Some loops repeat statements until a condition is False; o Others repeat statements until a condition is True. o There are also loops that repeat statements a specific number of times. The following looping statements are available in VBScript: o Do...Loop: Loops while or until a condition is True. o While...Wend: Loops while a condition is True. o For...Next: Uses a counter to run statements a specified number of times. o For Each...Next: Repeats a group of statements for each item in a collection or each element of an array.

1) Using Do Loops We can use Do...Loop statements to run a block of statements an indefinite number of times. The statements are repeated either while a condition is True or until a condition becomes True. a) Repeating Statements While a Condition is True Repeats a block of statements while a condition is True or until a condition becomes True i) Do While condition Statements --------------------Loop Or, we can use this below syntax: Example: Dim x Do While x<5 x=x+1 Msgbox "Hello G.C.Reddy" Msgbox "Hello QTP" Loop ii) Do Statements --------------------Loop While condition Example: Dim x x=1 Do Msgbox "Hello G.C.Reddy" Msgbox "Hello QTP" x=x+1 Loop While x<5 b) Repeating a Statement Until a Condition Becomes True iii) Do Until condition

Statements --------------------Loop Or, we can use this below syntax: Example: Dim x Do Until x=5 x=x+1 Msgbox "G.C.Reddy" Msgbox "Hello QTP" Loop Or, we can use this below syntax: iv) Do Statements --------------------Loop Until condition Or, we can use this below syntax: Example: Dim x x=1 Do Msgbox Hello G.C.Reddy Msgbox "Hello QTP" x=x+1 Loop Until x=5 2 While...Wend Statement Executes a series of statements as long as a given condition is True. Syntax: While condition Statements --------------------Wend Example: Dim x x=0 While x<5 x=x+1

msgbox "Hello G.C.Reddy" msgbox "Hello QTP" Wend 3) For...Next Statement Repeats a group of statements a specified number of times. Syntax: For counter = start to end [Step step] statements Next Example: Dim x For x= 1 to 5 step 1 Msgbox "Hello G.C.Reddy" Next 4) For Each...Next Statement Repeats a group of statements for each element in an array or collection. Syntax: For Each item In array Statements Next Example: (1 Dim a,b,x (3) a=20 b=30 x(0)= "Addition is "& a+b x(1)="Substraction is " & a-b x(2)= "Multiplication is " & a*b x(3)= "Division is " & a/b For Each element In x msgbox element Next Example: (2 MyArray = Array("one","two","three","four","five") For Each element In MyArray msgbox element

Next VB Script Procedures User Defined Functions In VBScript, there are two kinds of procedures available; the Sub procedure and the Function procedure. 1) Sub Procedures A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub statements) that perform actions but don't return a value. A Sub procedure can take arguments (constants, variables, or expressions that are passed by a calling procedure). If a Sub procedure has no arguments, its Sub statement must include an empty set of parentheses (). Syntax: Sub Procedure name () Statements --------------------End Sub Or Sub Procedure name (argument1, argument2) Statements --------------------End Sub Example: 1 Sub ConvertTemp() temp = InputBox("Please enter the temperature in degrees F.", 1) MsgBox "The temperature is " & Celsius(temp) & " degrees C." End Sub Example: 2

2) Function Procedures A Function procedure is a series of VBScript statements enclosed by the Function and End Function statements. A Function procedure is similar to a Sub procedure, but can also return a value. A Function procedure can take arguments (constants, variables, or expressions that are passed to it by a calling procedure). If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. A Function returns a value by assigning a value to its name in one or more statements of the procedure. The return type of a Function is always a Variant. Syntax: Function Procedure name () Statements --------------------End Function Or Function Procedure name (argument1, argument2) Statements --------------------End Function Example: 1 Function Celsius(fDegrees) Celsius = (fDegrees - 32) * 5 / 9 End Function Example: 2 Function cal(a,b,c) cal = (a+b+c) End Function

3) Getting Data into and out of Procedures o Each piece of data is passed into our procedures using an argument. o Arguments serve as placeholders for the data we want to pass into our procedure. We can name our arguments any valid variable name. o When we create a procedure using either the Sub statement or the Function statement, parentheses must be included after the name of the procedure. o Any arguments are placed inside these parentheses, separated by commas. 4) Using Sub and Function Procedures in Code A Function in our code must always be used on the right side of a variable assignment or in an expression. For example: Temp = Celsius(fDegrees) -OrMsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees." To call a Sub procedure from another procedure, type the name of the procedure along with values for any required arguments, each separated by a comma. The Call statement is not required, but if you do use it, you must enclose any arguments in parentheses. The following example shows two calls to the MyProc procedure. One uses the Call statement in the code; the other doesn't. Both do exactly the same thing. Call MyProc(firstarg, secondarg) MyProc firstarg, secondarg Notice that the parentheses are omitted in the call when the Call statement isn't used. 5) Examples: (here, I used Flight Reservation Application for creating Functions, why because, It is the default

application for QTP, anybody can practice easily...G C Reddy) '******************************************* ' Login Operation '******************************************* Function Login(Agent,Pwd) SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set Agent Dialog("Login").WinEdit("Password:").Set Pwd Dialog("Login").WinButton("OK").Click If Window("Flight Reservation").Exist(10) Then Login="Login Operation Sucessful" 'Msgbox Login else Login="Login Operation Unsucessful" Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click Dialog("Login").WinButton("Cancel").Click 'Msgbox Login End If End Function '*************************************** ' Closing Application '*************************************** Function Close_App() if Window("Flight Reservation").Exist(3) Then Window("Flight Reservation").Close End If End Function '*************************************** ' Open Order '*************************************** Function Open_Order(ord) ordnum=0 On Error Resume Next Window("Flight Reservation").Activate Window("Flight Reservation").WinButton("Button").Click Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set ord Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click ordnum=Window("Flight Reservation").WinEdit("Order No:").GetROProperty ("text") ordnum=cdbl (ordnum) If ord=ordnum Then Open_Order= "Order Number "&ordnum&" Opened Sucuessfully" 'Msgbox Open_Order

else Open_Order= "Order Number "&ordnum&" Not Opened/ Not Available" Window("Flight Reservation").Dialog("Open Order").Dialog("Flight Reservations").WinButton("OK").Click Window("Flight Reservation").Dialog("Open Order").WinButton("Cancel").Click 'Msgbox Open_Order End If End Function '****************************************** ' Update Order '****************************************** Function Update_Order(Tickets) Window("Flight Reservation").Activate Window("Flight Reservation").WinEdit("Tickets:").Set Tickets Window("Flight Reservation").WinButton("Update Order").Click wait(10) update=Window("Flight Reservation").ActiveX("Threed Panel Control").GetROProperty ("text") If update="Update Done..." Then Update_Order= "Order Updated Sucussfully" 'Msgbox Update_Order Else Window("Flight Reservation").Dialog("Flight Reservations").WinButton("OK").Click Update_Order= "Order Not Updated" 'Msgbox Update_Order End If End Function '****************************************** ' Function to send a mail '****************************************** Function SendMail(SendTo, Subject, Body, Attachment) Set otl=CreateObject("Outlook.Application") Set m=otl.CreateItem(0) m.to=SendTo m.Subject=Subject m.Body=Body If (Attachment <> "") Then Mail.Attachments.Add(Attachment) End If m.Send otl.Quit Set m = Nothing Set otl = Nothing End Function Call SendMail("ranga@ranga.com","hi","This is test mail for testing","")

VB Script Errors Generally Errors in VB Script are 2 Types 1) VB Script Run-time Errors VB Script run-time errors are errors that result when your VBScript script attempts to perform an action that the system cannot execute. VBScript run-time errors occur while your script is being executed; when variable expressions are being evaluated, and memory is being dynamic allocated. Error Number Description: 429 ActiveX component can't create object 507 An exception occurred 449 Argument not optional 17 Can't perform requested operation 430 Class doesn't support Automation 506 Class not defined 11 Division by zero 48 Error in loading DLL 5020 Expected ')' in regular expression 5019 Expected ']' in regular expression 432 File name or class name not found during Automation operation 92 For loop not initialized 5008 Illegal assignment 51 Internal error 505 Invalid or unqualified reference 481 Invalid picture 5 Invalid procedure call or argument 5021 Invalid range in character set 94 Invalid use of Null 448 Named argument not found 447 Object doesn't support current locale setting 445 Object doesn't support this action 438 Object doesn't support this property or method 451 Object not a collection 504 Object not safe for creating 503 Object not safe for initializing 502 Object not safe for scripting 424 Object required 91 Object variable not set 7 Out of Memory 28 Out of stack space 14 Out of string space 6 Overflow 35 Sub or function not defined 9 Subscript out of range 5017 Syntax error in regular expression

462 The remote server machine does not exist or is unavailable 10 This array is fixed or temporarily locked 13 Type mismatch 5018 Unexpected quantifier 500 Variable is undefined 458 Variable uses an Automation type not supported in VBScript 450 Wrong number of arguments or invalid property assignment 2) VB Script Syntax Errors VBScript syntax errors are errors that result when the structure of one of your VBScript statements violates one or more of the grammatical rules of the VBScript scripting language. VBScript syntax errors occur during the program compilation stage, before the program has begun to be executed. Error Number Description: 1052 Cannot have multiple default property/method in a Class 1044 Cannot use parentheses when calling a Sub 1053 Class initialize or terminate do not have arguments 1058 'Default' specification can only be on Property Get 1057 'Default' specification must also specify 'Public' 1005 Expected '(' 1006 Expected ')' 1011 Expected '=' 1021 Expected 'Case' 1047 Expected 'Class' 1025 Expected end of statement 1014 Expected 'End' 1023 Expected expression 1015 Expected 'Function' 1010 Expected identifier 1012 Expected 'If' 1046 Expected 'In' 1026 Expected integer constant 1049 Expected Let or Set or Get in property declaration 1045 Expected literal constant 1019 Expected 'Loop' 1020 Expected 'Next' 1050 Expected 'Property' 1022 Expected 'Select' 1024 Expected statement 1016 Expected 'Sub' 1017 Expected 'Then' 1013 Expected 'To' 1018 Expected 'Wend' 1027 Expected 'While' or 'Until' 1028 Expected 'While,' 'Until,' or end of statement 1029 Expected 'With' 1030 Identifier too long

1014 Invalid character 1039 Invalid 'exit' statement 1040 Invalid 'for' loop control variable 1013 Invalid number 1037 Invalid use of 'Me' keyword 1038 'loop' without 'do' 1048 Must be defined inside a Class 1042 Must be first statement on the line 1041 Name redefined 1051 Number of arguments must be consistent across properties specification 1001 Out of Memory 1054 Property Set or Let must have at least one argument 1002 Syntax error 1055 Unexpected 'Next' 1015 Unterminated string constant VB Script Functions Built-In Functions of VB Script o Conversions (25) o Dates/Times (19) o Formatting Strings (4) o Input/Output (3) o Math (9) o Miscellaneous (3) o Rounding (5) o Strings (30) o Variants (8) Important Functions

1) Abs Function Returns the absolute value of a number. Dim num num=abs(-50.33) msgbox num 2) Array Function Returns a variant containing an Array Dim A A=Array("hyderabad","chennai","mumbai") msgbox A(0) ReDim A(5) A(4)="nellore" msgbox A(4) 3) Asc Function Returns the ANSI character code corresponding to the first letter in a string. Dim num num=Asc("A") msgbox num * It returns the value 65 * 4) Chr Function Returns the character associated with the specified ANSI character code. Dim char Char=Chr(65) msgbox char * It returns A * 5) CInt Function Returns an expression that has been converted to a Variant of subtype Integer.

Dim num num=123.45 myInt=CInt(num) msgbox MyInt 6) Date Function Returns the Current System Date. Dim mydate mydate=Date msgbox mydate 7) Day Function Ex1) Dim myday myday=Day("17,December,2009") msgbox myday Ex2) Dim myday mydate=date myday=Day(Mydate) msgbox myday 8) DateDiff Function Returns the number of intervals between two dates. Dim Date1, Date2, x Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("yyyy", Date1, Date2) Msgbox x 'Differnce in Years Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("q", Date1, Date2) Msgbox x 'Differnce in Quarters Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("m", Date1, Date2)

Msgbox x 'Differnce in Months Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("w", Date1, Date2) Msgbox x 'Differnce in weeks Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("d", Date1, Date2) Msgbox x 'Differnce in days Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("h", Date1, Date2) Msgbox x 'Differnce in Hours Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("n", Date1, Date2) Msgbox x 'Differnce in Minutes Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("s", Date1, Date2) Msgbox x 'Differnce in Seconds Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("y", Date1, Date2) Msgbox x 'Differnce in day of years Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("a", Date1, Date2) Msgbox x 'Error Date1=#10-10-09# Date2=#10-10-11# x=DateDiff(Date1, Date2) Msgbox x 'Error

9) Hour Function Returns a whole number between 0 and 23, inclusive, representing the hour of the day. Dim mytime, Myhour mytime=Now myhour=hour (mytime) msgbox myhour 10) Join Function Returns a string created by joining a number of substrings contained in an array. Dim mystring, myarray(3) myarray(0)="Chandra " myarray(1)="Mohan " myarray(2)="Reddy" mystring=Join(MyArray) msgbox mystring 11) Eval Function Evaluates an expression and returns the result. 12) Time Function Returns a Variant of subtype Date indicating the current system time. Dim mytime mytime=Time msgbox mytime 13) VarType Function Returns a value indicating the subtype of a variable. Dim x,y x=100 y=VarType(x) Msgbox y '2 (Integer)

x="Hyderabad" y=VarType(x) Msgbox y '8 (String) x=#10-10-10# y=VarType(x) Msgbox y '7(Date format) x=100.56 y=VarType(x) Msgbox y ' 5(Double) y=VarType(a) Msgbox y '0 (Empty) Set x =CreateObject("Scripting.FileSystemObject") y=VarType(x) Msgbox y '9(Automation Object)

14) Left Function Dim Val, x,y Val="Hyderabad" x=Left(Val,3) Msgbox x 'Hyd Val=100 x=Left(Val,1) Msgbox x '1 Val="Hyderabad" x=Left(Val,0) Msgbox x 'Null Val="Hyderabad" x=Left(Val,12) Msgbox x 'Hyderabad Val=#10-10-10# x=Left(Val,3) Msgbox x '10/ Val="Hyderabad" x=Left(Val) Msgbox x 'Error (Lengnth is Manditory)

14) Right Function Dim AnyString, MyStr AnyString = "Hello World" ' Define string. MyStr = Right(AnyString, 1) ' Returns "d". MyStr = Right(AnyString, 6) ' Returns " World". MyStr = Right(AnyString, 20) ' Returns "Hello World". 15) Len Function Returns the number of characters in a string or the number of bytes required to store a variable. Ex 1): Dim Mystring mystring=Len("G.C.Reddy") msgbox mystring Ex 2): Dim Mystring Mystring=Inputbox("Enter a Value") Mystring=Len(Mystring) Msgbox Mystring 16) Mid Function Returns a specified number of characters from a string. Dim Val, x,y Val="Hyderabad" x=Mid(Val,3,4) Msgbox x 'dera Val=100 x=Mid(Val,1) Msgbox x '100 Val="Hyderabad" x=Mid(Val,6,7) Msgbox x 'abad Val="Hyderabad" x=Mid(Val,6,1) Msgbox x 'a Val="Hyderabad" x=Mid(Val,6,0)

Msgbox x 'Null Val="Hyderabad" x=Mid(Val,12) Msgbox x 'Null Val=#10-10-10# x=Mid(Val,3,3) Msgbox x '/10 Val=#2010-10-10# x=Mid(Val,5) Msgbox x '/2010 Val="Hyderabad" x=Mid(Val) Msgbox x 'Error

17) Timer Function Returns the number of seconds that have elapsed since 12:00 AM (midnight). Function myTime(N) Dim StartTime, EndTime StartTime = Timer For I = 1 To N Next EndTime = Timer myTime= EndTime - StartTime msgbox myTime End Function Call myTime(2000) 17) isNumeric Function Dim MyVar, MyCheck MyVar = 53 MyCheck = IsNumeric(MyVar) msgbox MyCheck MyVar = "459.95" MyCheck = IsNumeric(MyVar) msgbox MyCheck MyVar = "45 Help" MyCheck = IsNumeric(MyVar)

msgbox MyCheck * It Returns True/False like Result * 18) Inputbox Function Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns the contents of the text box. Dim Input Input = InputBox("Enter your name") MsgBox ("You entered: " & Input) 19) Msgbox Function Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked. Dim MyVar MyVar = MsgBox ("Hello World!", 65, "MsgBox Example") 20) CreateObject creates and returns reference of the filesytemobject to an Automation object. It can be used for performing operations on computer file system Set objFso=createobject ("Scripting.FileSystemObject") 'creates and returns reference of the Excel bject to an Automation object. It can be used for performing operations on Spreed sheet (Ms-Excel files) Set objExcel = CreateObject("Excel.Application") 'creates and returns reference of the Word Object to an Automation object. It can be used for performing operations on Ms-Word documents Set objWord = CreateObject("Word.Application")

'creates and returns reference of the Database Connection to an Automation object. It can be used for Connecting, opening and Closing databases Set objConnection = CreateObject("ADODB.Connection")

'creates and returns reference of the Database Recordset to an Automation object. It can be used for performing operations on database tables(Records) Set objRecordSet = CreateObject("ADODB.Recordset") 'creates and returns reference of the Ms-Power point object to an Automation object. It can be used for performing operations on Power point presentations Set objPPT = CreateObject("PowerPoint.Application") Set xmldoc = WScript.CreateObject("msxml2.domdocument") 21) Round Returns a number rounded to a specified number of decimal places. Dim num num=172.499 num=Round(num) msgbox num 22) StrReverse It returns reverse value of the given sring x=strreverse ("dabaraedyh") msgbox x 23) strComp It compares two strings based on ASCII Values and Returens -1 (1st less than 2nd ), 0 (Equal) and 1 (1st greater than 2nd)

Dim x, y x="cd": y="bcd" comp=strcomp(x,y) msgbox comp 24) Replace It replace a sub string with given value (another sub string) mystring=Replace("kb script", "k","v") msgbox mystring Apr 5, 2010 VB Script Objects VB Script Objects a) FileSystemObject

Scripting allows us to process drives, folders, and files using the FileSystemObject (FSO) object model. Creating FileSystemObject: Set Variable=CreateObject("Scripting.FileSystemObject") Example: Dim objFso Set objFso=CreateObject("Scripting.FileSystemObject") objFso.CteateTextFile("D:\ranga.txt") b) Dictionary

Creating Dictionary Object: Set Variable=CreateObject("Scripting.Dictionary") Example: c) Excel Application

Creating Excel Object: Set Variable=CreateObject("Excel.Application") Example: d) Word Application

Creating Word Object: Set Variable=CreateObject("Word.Application") Example: e) Shell

Creating Shell Object: Set Variable= WScript.CreateObject("Wscript.Shell") Example: f) Network

Creating Network Object: Set Variable= WScript.CreateObject("WScript.Network") Example: g) PowerPoint

Creating PowerPointObject: Set Variable=CreateObject("PowerPoint.Application") Example: h) ADODB Connection

The ADO Connection Object is used to create an open connection to a data source. Through this connection, you can access and manipulate a database.

Creating Database Connection Object: Set Variable=CreateObject("ADODB.Connection") Example: i) ADODB RecordSet

The ADO Recordset object is used to hold a set of records from a database table. A Recordset object consist of records and columns (fields).

Creating Database RecordSet Object: Set Variable=CreateObject("ADODB.RecordSet") Example: j) ADODB Command

The ADO Command object is used to execute a single query against a database. The query can perform actions like creating, adding, retrieving, deleting or updating records.

Creating Database Command Object: Set Variable=CreateObject("ADODB.Command") Example: k) Error

Creating Error Object:

l) RegExp Creating RegExp Object:

Set objReg=CreateObject("vbscript.regexp") m) Internet Explorer

n) Outlook Express

a) Dictionary Object Dictionary Object that stores data key, item pairs. A Dictionary object is the equivalent of a PERL associative array/Hash Variable. Items can be any form of data, and are stored in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is usually an integer or a string, but can be anything except an array.

Creating a Dictionary Object: Set objDictionary = CreateObject("Scripting.Dictionary") Dictionary Objects Methods: Add Method Adds a key and item pair to a Dictionary object Exists Method Returns true if a specified key exists in the Dictionary object, false if it does not. Items Method Returns an array containing all the items in a Dictionary object.

Keys Method Returns an array containing all existing keys in a Dictionary object. Remove Method Removes a key, item pair from a Dictionary object. RemoveAll Method The RemoveAll method removes all key, item pairs from a Dictionary object. Example: Dim cities Set cities = CreateObject("Scripting.Dictionary") cities.Add "h", "Hyderabad" cities.Add "b", "Bangalore" cities.Add "c", "Chennai" Dictionary Objects Properties: Count Property Returns the number of items in a collection or Dictionary object. Read-only. CompareMode Property Sets and returns the comparison mode for comparing string keys in a Dictionary object. Key Property Sets a key in a Dictionary object. Item Property Sets or returns an item for a specified key in a Dictionary object. For collections, returns an item based on the specified key. Read/write. Examples: 1) Add Elements to a Dictionary

Set objDictionary = CreateObject("Scripting.Dictionary") objDictionary.Add "Printer 1", "Printing" objDictionary.Add "Printer 2", "Offline"

objDictionary.Add "Printer 3", "Printing" 2) Delete All Elements from a Dictionary Set objDictionary = CreateObject("Scripting.Dictionary") objDictionary.Add "Printer 1", "Printing" objDictionary.Add "Printer 2", "Offline" objDictionary.Add "Printer 3", "Printing" colKeys = objDictionary.Keys Wscript.Echo "First run: " For Each strKey in colKeys Wscript.Echo strKey Next objDictionary.RemoveAll colKeys = objDictionary.Keys Wscript.Echo VbCrLf & "Second run: " For Each strKey in colKeys Wscript.Echo strKey Next 3) Delete One Element from a Dictionary Set objDictionary = CreateObject("Scripting.Dictionary") objDictionary.Add "Printer 1", "Printing" objDictionary.Add "Printer 2", "Offline" objDictionary.Add "Printer 3", "Printing" colKeys = objDictionary.Keys Wscript.Echo "First run: " For Each strKey in colKeys Wscript.Echo strKey Next objDictionary.Remove("Printer 2") colKeys = objDictionary.Keys

Wscript.Echo VbCrLf & "Second run: " For Each strKey in colKeys Wscript.Echo strKey Next 4) List the Number of Items in a Dictionary Set objDictionary = CreateObject("Scripting.Dictionary") objDictionary.Add "Printer 1", "Printing" objDictionary.Add "Printer 2", "Offline" objDictionary.Add "Printer 3", "Printing" Wscript.Echo objDictionary.Count

5) Verify the Existence of a Dictionary Key Set objDictionary = CreateObject("Scripting.Dictionary") objDictionary.Add "Printer 1", "Printing" objDictionary.Add "Printer 2", "Offline" objDictionary.Add "Printer 3", "Printing" If objDictionary.Exists("Printer 4") Then Wscript.Echo "Printer 4 is in the Dictionary." Else Wscript.Echo "Printer 4 is not in the Dictionary." End If

Apr 5, 2010 VBScript Coding Conventions Coding conventions are suggestions are designed to help us write code using VB Script. Coding conventions can include the following: Naming conventions for objects, variables, and procedures

Commenting conventions Text formatting and indenting guidelines The main reason for using a consistent set of coding conventions is to standardize the structure and coding style of a script or set of scripts so that we and others can easily read and understand the code. Using good coding conventions results in clear, precise, and readable source code that is consistent with other language conventions and is intuitive. Variable Naming Conventions To enhance readability and consistency, we have to use the following prefixes with descriptive names for variables in our VBScript code. Subtype Prefix Example ---------------------------------------------Boolean bln blnFound ----------------------------------------------Byte byt bytRasterData ----------------------------------------------------Date (Time) dtm dtmStart ---------------------------------------------------Double dbl dblTolerance ----------------------------------------------------Error err errOrderNum ----------------------------------------------------Integer int IntQuantity ----------------------------------------------------Long lng lngDistance ----------------------------------------------------Object obj objCurrent ----------------------------------------------------Single sng sngAverage ----------------------------------------------------String str strFirstName ----------------------------------------------------Object Naming Conventions: The following table lists recommended conventions for objects you may encounter while programming VBScript. Object type Prefix Example --------------------------------------------------3D Panel pnl pnlGroup ---------------------------------------------------

Animated button ani aniMailBox --------------------------------------------------Check box chk chkReadOnly --------------------------------------------------Combo box cbo cboEnglish --------------------------------------------------Command button cmd cmdExit --------------------------------------------------Common dialog dlg dlgFileOpen --------------------------------------------------Frame fra fraLanguage --------------------------------------------------Image img imgIcon --------------------------------------------------Label lbl lblHelpMessage --------------------------------------------------Line lin linVertical --------------------------------------------------List Box lst lstPolicyCodes --------------------------------------------------Spin spn spnPages --------------------------------------------------Text box txt txtLastName --------------------------------------------------Slider sld sldScale --------------------------------------------------Code Commenting Conventions All procedures should begin with a brief comment describing what they do. This description should not describe the implementation details (how it does it) because these often change over time, resulting in unnecessary comment maintenance work, or worse, erroneous comments. The code itself and any necessary inline comments describe the implementation. Arguments passed to a procedure should be described when their purpose is not obvious and when the procedure expects the arguments to be in a specific range. Return values for functions and variables that are changed by a procedure, especially through reference arguments, should also be described at the beginning of each procedure. Procedure header comments should include the following section headings. For examples, see the "Formatting Your Code" section that follows.

Section Heading

Comment Contents

Purpose: What the procedure does (not how). Assumptions: List of any external variable, control, or otherelement procedure. whose state affects this

Effects: List of the procedure's effect on each external variable, control, or other element. Inputs: Explanation of each argument that is not obvious. Each argument should be on a separate line with inline comments. Return Values: Explanation of the value returned.

Remember the following points: Every important variable declaration should include an inline comment describing the use of the variable being declared. Variables, controls, and procedures should be named clearly to ensure that inline comments are only needed for complex implementation details. At the beginning of your script, you should include an overview that describes the script, enumerating objects, procedures, algorithms, dialog boxes, and other system dependencies. Sometimes a piece of pseudocode describing the algorithm can be helpful. Formatting the Code Screen space should be conserved as much as possible, while still allowing code formatting to reflect logic structure and nesting. Here are a few suggestions: Indent standard nested blocks four spaces. Indent the overview comments of a procedure one space.

Indent the highest level statements that follow the overview comments four spaces, with each nested block indented an additional four spaces. The following code adheres to VBScript coding conventions. '********************************************************* ' Purpose: Locates the first occurrence of a specified user ' in the UserList array. ' Inputs: strUserList(): the list of users to be searched. ' strTargetUser: the name of the user to search for. ' Returns: The index of the first occurrence of the strTargetUser ' in the strUserList array. ' If the target user is not found, return -1. '********************************************************* Function intFindUser (strUserList(), strTargetUser) Dim i ' Loop counter. Dim blnFound ' Target found flag intFindUser = -1 i = 0 ' Initialize loop counter Do While i <= Ubound(strUserList) and Not blnFound If strUserList(i) = strTargetUser Then blnFound = True ' Set flag to True intFindUser = i ' Set return value to loop count End If i = i + 1 ' Increment loop counter Loop End Function Posted by G.Chandra Mohan Reddy at 11:57 AM Email This BlogThis! Share to Twitter Share to Facebook Share to Google Buzz 0 comments: Post a Comment

Newer Post Older Post Home Subscribe to: Post Comments (Atom) QTP Training in Hyderabad Software Testing VB Script for QTP QTP Scripting QTP Guide QTP Certification QTP Resumes Software Testing Documents Manual Testing Documents QTP Framework

QTP Group Subscribe to G C Reddy QTP Group Email: Visit this group About Me G.Chandra Mohan Reddy I am G C Reddy, Working as a Test Consultant in Hyderabad, INDIA. I am also providing Online training for QTP. View my complete profile Search The Web Loading... Page Views gc Blog Archive ? 2010 (104) ? April (56) HP QTP VB Script syntax rules and guidelines qtp real-time script example Dynamic Handling of Object Repositories VB Script Properties VB Script Objects Methods QTP Model Resume 5+ years experience VB Script Errors QTP 3+ Years Exp Resume VBScript Coding Conventions Looping Through Code VB Script String Functions Constants VB Script Data Types Comments Scripting Languages Vs Programming Languages VB Script for QTP QTP Other Topics Network Administration Automation Object Model

Word Scripts File System Operations Recovery Scenarios Virtual Object Configuration Regular Expressions Environment Variables VB Script Functions Reporting Defects Analyzing Test Results & Reporting Database Scripts-II Debugging Tests VB Script Fundamentals And Features Adding Comments Step Generator Inserting Transaction Points Inserting Output values Inserting Checkpoints Web Scripts-II Data Table Methods Keyword Driven Methodology Object Identification Configuration Test Object Model Recording Tests QTP Commands User Defined Functions An overview on Test Automation QTP Certification VB Script Examples-II QTP Model Resumes QTP Interview Questions QTP Training Programs QTP Framework VB Script for QTP QTP Scripting QTP Guide ? March (39) ? February (3) ? January (6) . VB Script General Examples

1) Read a value and find size of the value

Dim val: val=Inputbox("Enter value for val: ") val_length =Len(val) msgbox "Size of "&val&" is "&val_length 2) Read a value and find whether the value is numeric or not? Dim val: val=Inputbox("Enter value for val: ") val_type =IsNumeric(val) If val_type = true Then msgbox "val is Numeric" else msgbox "val is not Numeric" End If 3)'Read a value and find whether the value is Date type data or not? Dim val: val=Inputbox("Enter value for val: ") val_type =IsDate(val) If val_type = true Then msgbox "val is Date type data" else msgbox "val is not date type" End If 4)Read a value and Verify whether the value is 10-digit number or not and started with 9 0r 8. 'Then Display it is a valid mobile number Dim val,val_Length, val_Numeric, val_Start val=Inputbox("Enter value for val: ") val_Length= Len(val) val_Numeric=IsNumeric(val) val_Start=Left(val,1) If val_Length=10 and val_Numeric and val_Start=9 or val_Start=8 Then msgbox val&" is a valid mobile number " Else msgbox val&" is not a valid mobile number " End If 5) 'Read a mobile number and verify the series 'if it starts with 92478 or 92471 then display it is TataIndicom number 'if it starts with 98490 or 98480 then display it is Airtel number Dim val, val_Length,val_Numeric,val_Series,val_Start val=Inputbox("Enter value for val: ") val_Length= Len(val)

val_Numeric=IsNumeric(val) val_Start=Left(val,1) val_Series=Left(val,5) If val_Numeric=true Then If val_Length=10 and val_Start=9 Then If val_Series = 92478 or val_Series=92471 Then msgbox "It is TataIndicom Number" ElseIf val_Series=98490 or val_Series = 98480 then msgbox "It is Airtel Number" End If Else msgbox val&" is not a valid mobile number " End If Else msgbox val& " is Invalid data" End If 6) Read a Value and Verify weather the value is started with Alfa bytes or not? (First letter should be Alfa byte)

Dim val, val_Asc val=Inputbox("enter a value") val_Asc=Asc(val) Msgbox val_Asc If val_Asc>=65 and val_Asc<=90 or val_Asc>=97 and val_Asc<=122Then msgbox val&" is an Alphabet" Else msgbox val&" is not an Alphabet" End If 7) Read a value and Verify weather the value is Alfa bytes are not? Dim str, valAsc, flag,i Dim strlen, counter,valsingle counter=0 str=Inputbox("enter a string value") strlen= Len(str) For i=1 to strlen step 1 valsingle=Mid(str,i,1) valAsc=Asc(valsingle)

If valAsc>=65 and valAsc<=90 or valAsc>=97 and valAsc<=122Then flag=1 counter=counter+1 Else flag=0 End If Next msgbox "No.of characters " &counter If counter=strlen and flag=1Then msgbox str&" is an Alphabetic value" Else msgbox str&" is not an Alphabetic value" End If

Anda mungkin juga menyukai