vb script integratrd

Upload: rajumno

Post on 07-Apr-2018

233 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 VB Script Integratrd

    1/26

    What Is VBScript?

    Microsoft Visual Basic Scripting Edition, the newest member of the Visual Basic familyof programming languages, brings active scripting to a wide variety of environments,including Web client scripting in Microsoft Internet Explorer and Web server scripting

    in Microsoft Internet Information Server.Easy to Use and Learn

    If you already know Visual Basic or Visual Basic for Applications, VBScript will be veryfamiliar. Even if you don't know Visual Basic, once you learn VBScript, you're on yourway to programming with the whole family of Visual Basic languages. Although youcan learn about VBScript in just these few Web pages, they don't teach you how toprogram. To get started programming, take a look at Step by Step books availablefrom Microsoft Press.

    ActiveX ScriptingVBScript talks to host applications using ActiveX Scripting. With ActiveX Scripting,browsers and other host applications don't require special integration code for eachscripting component. ActiveX Scripting enables a host to compile scripts, obtain andcall entry points, and manage the namespace available to the developer. With ActiveXScripting, language vendors can create standard language run times for scripting.Microsoft will provide run-time support for VBScript. Microsoft is working with variousInternet groups to define the ActiveX Scripting standard so that scripting engines canbe interchangeable. ActiveX Scripting is used in Microsoft Internet Explorer and inMicrosoft Internet Information Server.

    VBScript in Other Applications and Browsers

    As a developer, you can license VBScript source implementation at no charge for usein your products. Microsoft provides binary implementations of VBScript for the 32-bitWindows API, the 16-bit Windows API, and the Macintosh. VBScript is integratedwith World Wide Web browsers. VBScript and ActiveX Scripting can also be used as ageneral scripting language in other applications.

    What Are VBScript Data Types?

    VBScript has only one data type called a Variant . A Variant is a special kind of datatype that can contain different kinds of information, depending on how it's used.Because Variant is the only data type in VBScript, it's also the data type returned byall functions in VBScript.

  • 8/6/2019 VB Script Integratrd

    2/26

    At its simplest, a Variant can contain either numeric or string information. A Variantbehaves as a number when you use it in a numeric context and as a string when youuse it in a string context. That is, if you're working with data that looks like numbers,VBScript assumes that it is numbers and does the thing that is most appropriate fornumbers. Similarly, if you're working with data that can only be string data, VBScript

    treats it as string data. Of course, you can always make numbers behave as strings byenclosing them in quotation marks (" ").

    Variant Subtypes

    Beyond the simple numeric or string classifications, a Variant can make furtherdistinctions about the specific nature of numeric information. For example, you canhave numeric information that represents a date or a time. When used with otherdate or time data, the result is always expressed as a date or a time. Of course, youcan also have a rich variety of numeric information ranging in size from Booleanvalues to huge floating-point numbers. These different categories of information that

    can be contained in a Variant are called subtypes. Most of the time, you can just putthe kind of data you want in a Variant , and the Variant behaves in a way that is mostappropriate for the data it contains.

    The following table shows the subtypes of data that a Variant can contain.

    Subtype Description

    Empty Variant is uninitialized. Value is 0 for numeric variables or azero-length string ("") for string variables.

    Null Variant intentionally contains no valid data.Boolean Contains either True or False .

    Byte Contains integer in the range 0 to 255.

    Integer Contains integer in the range -32,768 to 32,767.

    Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807.

    Long Contains integer in the range -2,147,483,648 to 2,147,483,647.

    Single Contains a single-precision, floating-point number in the range-3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.

    Double Contains a double-precision, floating-point number in the range-1.79769313486232E308 to -4.94065645841247E-324 fornegative values; 4.94065645841247E-324 to1.79769313486232E308 for positive values.

  • 8/6/2019 VB Script Integratrd

    3/26

    Date(Time)

    Contains a number that represents a date between January 1,100 to December 31, 9999.

    String Contains a variable-length string that can be up toapproximately 2 billion characters in length.

    Object Contains an object.

    Error Contains an error number.

    You can use conversion functions to convert data from one subtype to another. Inaddition, the VarType function returns information about how your data is storedwithin a Variant .

    What Is a Variable?

    A variable is a convenient placeholder that refers to a computer memory locationwhere you can store program information that may change during the time your scriptis running. For example, you might create a variable called ClickCount to store thenumber of times a user clicks an object on a particular Web page. Where the variableis stored in computer memory is unimportant. What's important is that you only haveto refer to a variable by name to see its value or to change its value. In VBScript,variables are always of one fundamental data type, Variant .

    Declaring Variables

    You declare variables explicitly in your script using the Dim statement, the Public

    statement, and the Private statement. For example:Dim DegreesFahrenheitYou declare multiple variables by separating each variable name with a comma. Forexample:Dim Top, Bottom, Left, Right

    You can also declare a variable implicitly by simply using its name in your script.That's not generally a good practice because you could misspell the variable name inone or more places, causing unexpected results when your script is run. For thatreason, the Option Explicit statement is available to require explicit declaration ofall variables. The Option Explicit statement should be the first statement in yourscript.

    Naming Restrictions

    Variable names follow the standard rules for naming anything in VBScript. A variablename:

    Must begin with an alphabetic character. Cannot contain an embedded period.

  • 8/6/2019 VB Script Integratrd

    4/26

    Must not exceed 255 characters. Must be unique in the scope in which it is declared.

    Scope and Lifetime of Variables

    A variable's scope is determined by where you declare it. When you declare a variablewithin a procedure, only code within that procedure can access or change the valueof that variable. It has local scope and is called a procedure-level variable. If youdeclare a variable outside a procedure, you make it recognizable to all the proceduresin your script. This is a script-level variable, and it has script-level scope.

    How long a variable exists is its lifetime. The lifetime of a script-level variableextends from the time it's declared until the time the script is finished running. Atprocedure level, a variable exists only as long as you are in the procedure. When theprocedure exits, the variable is destroyed. Local variables are ideal as temporarystorage space when a procedure is executing. You can have local variables of the

    same name in several different procedures because each is recognized only by theprocedure in which it is declared.

    Assigning Values to Variables

    Values are assigned to variables creating an expression as follows: the variable is onthe left side of the expression and the value you want to assign to the variable is onthe right. For example:B = 200

    Scalar Variables and Array Variables

    Much of the time, you just want to assign a single value to a variable you've declared.A variable containing a single value is a scalar variable. Other times, it's convenient toassign more than one related value to a single variable. Then you can create avariable that can contain a series of values. This is called an array variable. Arrayvariables and scalar variables are declared in the same way, except that thedeclaration of an array variable uses parentheses ( ) following the variable name. Inthe following example, a single-dimension array containing 11 elements is declared:Dim A(10)

    Although the number shown in the parentheses is 10, all arrays in VBScript are zero-based, so this array actually contains 11 elements. In a zero-based array, the number

    of array elements is always the number shown in parentheses plus one. This kind ofarray is called a fixed-size array.

    You assign data to each of the elements of the array using an index into the array.Beginning at zero and ending at 10, data can be assigned to the elements of an arrayas follows:

    A(0) = 256

  • 8/6/2019 VB Script Integratrd

    5/26

    A(1) = 324A(2) = 100. . .A(10) = 55

    Similarly, the data can be retrieved from any element using an index into the

    particular array element you want. For example:. . .SomeVariable = A(8). . .

    Arrays aren't limited to a single dimension. You can have as many as 60 dimensions,although most people can't comprehend more than three or four dimensions. Multipledimensions are declared by separating an array's size numbers in the parentheses withcommas. In the following example, the MyTable variable is a two-dimensional arrayconsisting 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.You can also declare an array whose size changes during the time your script isrunning. This is called a dynamic array. The array is initially declared within aprocedure 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 dmension. In the following example, ReDim setsthe initial size of the dynamic array to 25. A subsequent ReDim statement resizes thearray to 30, but uses the Preserve keyword to preserve the contents of the array asthe resizing takes place.ReDim MyArray(25). . .ReDim Preserve MyArray(30)

    There is no limit to the number of times you can resize a dynamic array, but youshould know that if you make an array smaller than it was, you lose the data in theeliminated elements.

    What Is a Constant?

    A constant is a meaningful name that takes the place of a number or string and neverchanges. VBScript defines a number of intrinsic constants . You can get informationabout these intrinsic constants from the VBScript Language Reference .

    Creating Constants

  • 8/6/2019 VB Script Integratrd

    6/26

    You create user-defined constants in VBScript using the Const statement. Using theConst statement, you can create string or numeric constants with meaningful namesand assign them literal values. For example:Const MyString = "This is my string."Const MyAge = 49

    Note that the string literal is enclosed in quotation marks (" "). Quotation marks arethe most obvious way to differentiate string values from numeric values. Date literals and time literals are represented by enclosing them in number signs (#). For example:Const CutoffDate = #6-1-97# You may want to adopt a naming scheme to differentiate constants from variables.This will prevent you from trying to reassign constant values while your script isrunning. For example, you might want to use a "vb" or "con" prefix on your constantnames, or you might name your constants in all capital letters. Differentiatingconstants from variables eliminates confusion as you develop more complex scripts.

    Operator Precedence

    When several operations occur in an expression, each part is evaluated and resolvedin a predetermined order called operator precedence. You can use parentheses tooverride the order of precedence and force some parts of an expression to beevaluated before others. Operations within parentheses are always performed beforethose outside. Within parentheses, however, standard operator precedence ismaintained.

    When expressions contain operators from more than one category, arithmeticoperators are evaluated first, comparison operators are evaluated next, and logicaloperators are evaluated last. Comparison operators all have equal precedence; that

    is, they are evaluated in the left-to-right order in which they appear. Arithmetic andlogical operators are evaluated in the following order of precedence.

    Arithmetic Comparison Logical

    Description Symbol Description Symbol Description Symbol

    Exponentiation ^ Equality = Logicalnegation

    Not

    Unary negation - Inequality Logicalconjunction

    And

    Multiplication * Less than < Logicaldisjunction

    Or

    Division / Greater than > Logicalexclusion

    Xor

    Integer division \ Less than or

  • 8/6/2019 VB Script Integratrd

    7/26

    equal to equivalence

    Modulusarithmetic

    Mod Greater thanor equal to

    >= Logicalimplication

    Imp

    Addition + Objectequivalence Is

    Subtraction -

    Stringconcatenation

    &

    When multiplication and division occur together in an expression, each operation isevaluated as it occurs from left to right. Likewise, when addition and subtractionoccur together in an expression, each operation is evaluated in order of appearance

    from left to right.The string concatenation (&) operator is not an arithmetic operator, but inprecedence it does fall after all arithmetic operators and before all comparisonoperators. The Is operator is an object reference comparison operator. It does notcompare objects or their values; it checks only to determine if two object referencesrefer to the same object.

    Controlling Program Execution

    You can control the flow of your script with conditional statements and looping

    statements. Using conditional statements, you can write VBScript code that makesdecisions and repeats actions. The following conditional statements are available inVBScript:

    If...Then...Else statement Select Case statement

    Making Decisions Using If...Then...Else

    The If...Then...Else statement is used to evaluate whether a condition is True orFalse 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 valueor variable with another. For information about comparison operators, seeComparison Operators . If...Then...Else statements can be nested to as many levels asyou need.

    Running Statements if a Condition is True

  • 8/6/2019 VB Script Integratrd

    8/26

    To run only one statement when a condition is True , use the single-line syntax for theIf...Then...Else statement. The following example shows the single-line syntax.Notice that this example omits the Else keyword.Sub FixDate()

    Dim myDate

    myDate = #2/13/95# If myDate < Now Then myDate = NowEnd Sub

    To run more than one line of code, you must use the multiple-line (or block) syntax.This syntax includes the End If statement, as shown in the following example:Sub AlertUser(value)

    If value = 0 ThenAlertLabel.ForeColor = vbRedAlertLabel.Font.Bold = TrueAlertLabel.Font.Italic = True

    End If

    End SubRunning Certain Statements if a Condition is True and Running Others if a

    Condition is False

    You can use an If...Then...Else statement to define two blocks of executablestatements: one block to run if the condition is True , the other block to run if thecondition is False .Sub AlertUser(value)

    If value = 0 ThenAlertLabel.ForeColor = vbRed

    AlertLabel.Font.Bold = TrueAlertLabel.Font.Italic = TrueElse

    AlertLabel.Forecolor = vbBlackAlertLabel.Font.Bold = FalseAlertLabel.Font.Italic = False

    End IfEnd Sub

    Deciding Between Several Alternatives

    A variation on the If...Then...Else statement allows you to choose from severalalternatives. Adding ElseIf clauses expands the functionality of the If...Then...Elsestatement so you can control program flow based on different possibilities. Forexample:Sub ReportValue(value)

    If value = 0 ThenMsgBox value

    ElseIf value = 1 Then

  • 8/6/2019 VB Script Integratrd

    9/26

    MsgBox valueElseIf value = 2 then

    Msgbox valueElse

    Msgbox "Value out of range!"

    End IfYou can add as many ElseIf clauses as you need to provide alternative choices.Extensive use of the ElseIf clauses often becomes cumbersome. A better way tochoose between several alternatives is the Select Case statement.

    Making Decisions with Select Case

    The Select Case structure provides an alternative to If...Then...ElseIf for selectivelyexecuting one block of statements from among multiple blocks of statements. ASelect Case statement provides capability similar to the If...Then...Else statement ,but it makes code more efficient and readable.

    A Select Case structure works with a single test expression that is evaluated once, atthe top of the structure. The result of the expression is then compared with thevalues for each Case in the structure. If there is a match, the block of statementsassociated with that Case is executed:

    Select Case Document.Form1.CardType.Options(SelectedIndex).TextCase "MasterCard"

    DisplayMCLogoValidateMCAccount

    Case "Visa"

    DisplayVisaLogoValidateVisaAccountCase "American Express"

    DisplayAMEXCOLogoValidateAMEXCOAccount

    Case ElseDisplayUnknownImagePromptAgain

    End SelectNotice that the Select Case structure evaluates an expression once at the top of thestructure. In contrast, the If...Then...ElseIf structure can evaluate a different

    expression for each ElseIf statement. You can replace an If...Then...ElseIf structurewith a Select Case structure only if each ElseIf statement evaluates the sameexpression.

    Using Loops to Repeat Code

  • 8/6/2019 VB Script Integratrd

    10/26

    Looping allows you to run a group of statements repeatedly. Some loops repeatstatements until a condition is False ; others repeat statements until a condition isTrue . There are also loops that repeat statements a specific number of times.

    The following looping statements are available in VBScript:

    Do...Loop : Loops while or until a condition is True . While...Wend : Loops while a condition is True . For...Next : Uses a counter to run statements a specified number of times. For Each...Next : Repeats a group of statements for each item in a collection

    or each element of an array.

    Using Do Loops

    You can use Do...Loop statements to run a block of statements an indefinite numberof times. The statements are repeated either while a condition is True or until a

    condition becomes True .Repeating Statements While a Condition is True

    Use the While keyword to check a condition in a Do...Loop statement. You can checkthe condition before you enter the loop (as shown in the following ChkFirstWhileexample), or you can check it after the loop has run at least once (as shown in theChkLastWhile example). In the ChkFirstWhile procedure, if myNum is set to 9 insteadof 20, the statements inside the loop will never run. In the ChkLastWhile procedure,the statements inside the loop run only once because the condition is already False .Sub ChkFirstWhile()

    Dim counter, myNumcounter = 0myNum = 20Do While myNum > 10

    myNum = myNum - 1counter = counter + 1

    LoopMsgBox "The loop made " & counter & " repetitions."

    End Sub

    Sub ChkLastWhile()

    Dim counter, myNumcounter = 0myNum = 9Do

    myNum = myNum - 1counter = counter + 1

    Loop While myNum > 10MsgBox "The loop made " & counter & " repetitions."

  • 8/6/2019 VB Script Integratrd

    11/26

    End Sub

    Repeating a Statement Until a Condition Becomes True

    You can use the Until keyword in two ways to check a condition in a Do...Loop

    statement. You can check the condition before you enter the loop (as shown in thefollowing ChkFirstUntil example), or you can check it after the loop has run at leastonce (as shown in the ChkLastUntil example). As long as the condition is False , thelooping occurs.Sub ChkFirstUntil()

    Dim counter, myNumcounter = 0myNum = 20Do Until myNum = 10

    myNum = myNum - 1counter = counter + 1

    LoopMsgBox "The loop made " & counter & " repetitions."End Sub

    Sub ChkLastUntil()Dim counter, myNumcounter = 0myNum = 1Do

    myNum = myNum + 1counter = counter + 1

    Loop Until myNum = 10MsgBox "The loop made " & counter & " repetitions."End Sub

    Exiting a Do...Loop Statement from Inside the Loop

    You can exit a Do...Loop by using the Exit Do statement. Because you usually want toexit only in certain situations, such as to avoid an endless loop, you should use theExit Do statement in the True statement block of an If...Then...Else statement. Ifthe condition is False , the loop runs as usual.

    In the following example, myNum is assigned a value that creates an endless loop.The If...Then...Else statement checks for this condition, preventing the endlessrepetition.

    Sub ExitExample()Dim counter, myNumcounter = 0myNum = 9

  • 8/6/2019 VB Script Integratrd

    12/26

    Do Until myNum = 10myNum = myNum - 1counter = counter + 1If myNum < 10 Then Exit Do

    Loop

    MsgBox "The loop made " & counter & " repetitions."End Sub

    Using While...Wend

    The While...Wend statement is provided in VBScript for those who are familiar withits usage. However, because of the lack of flexibility in While...Wend , it isrecommended that you use Do...Loop instead.

    Using For...Next

    You can use For...Next statements to run a block of statements a specific number oftimes. For loops, use a counter variable whose value is increased or decreased witheach repetition of the loop.

    For example, the following procedure causes a procedure called MyProc to execute 50times. The For statement specifies the counter variable x and its start and endvalues. The Next statement increments the counter variable by 1.

    Sub DoMyProc50Times()Dim xFor x = 1 To 50

    MyProcNextEnd Sub

    Using the Step keyword, you can increase or decrease the counter variable by thevalue you specify. In the following example, the counter variable j is incremented by2 each time the loop repeats. When the loop is finished, total is the sum of 2, 4, 6, 8,and 10.Sub TwosTotal()

    Dim j, totalFor j = 2 To 10 Step 2

    total = total + j

    NextMsgBox "The total is " & totalEnd Sub

    To decrease the counter variable, you use a negative Step value. You must specify anend value that is less than the start value. In the following example, the countervariable myNum is decreased by 2 each time the loop repeats. When the loop isfinished, total is the sum of 16, 14, 12, 10, 8, 6, 4, and 2.Sub NewTotal()

  • 8/6/2019 VB Script Integratrd

    13/26

    Dim myNum, totalFor myNum = 16 To 2 Step -2

    total = total + myNumNextMsgBox "The total is " & total

    End SubYou can exit any For...Next statement before the counter reaches its end value byusing the Exit For statement. Because you usually want to exit only in certainsituations, such as when an error occurs, you should use the Exit For statement in theTrue statement block of an If...Then...Else statement. If the condition is False , theloop runs as usual.

    Using For Each...Next

    A For Each...Next loop is similar to a For...Next loop. Instead of repeating thestatements a specified number of times, a For Each...Next loop repeats a group of

    statements for each item in a collection of objects or for each element of an array.This is especially helpful if you don't know how many elements are in a collection.

    VBScript Procedures

    Kinds of Procedures

    In VBScript there are two kinds of procedures; the Sub procedure and the Function procedure.

    Sub Procedures

    A Sub procedure is a series of VBScript statements, enclosed by Sub and End Substatements, that perform actions but don't return a value. A Sub procedure can takearguments (constants, variables, or expressions that are passed by a callingprocedure). If a Sub procedure has no arguments, its Sub statement must include anempty set of parentheses ().

    The following Sub procedure uses two intrinsic, or built-in, VBScript functions,MsgBoxand InputBox , to prompt a user for some information. It then displays theresults of a calculation based on that information. The calculation is performed in aFunction procedure created using VBScript. The Function procedure is shown after

    the following discussion.

    Sub ConvertTemp()temp = InputBox("Please enter the temperature in degrees F.", 1)MsgBox "The temperature is " & Celsius(temp) & " degrees C."

    End Sub

    Function Procedures

  • 8/6/2019 VB Script Integratrd

    14/26

    A Function procedure is a series of VBScript statements enclosed by the Function andEnd Function statements. A Function procedure is similar to a Sub procedure, butcan 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 Functionprocedure 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 ormore statements of the procedure. The return type of a Function is always a Variant .

    In the following example, the Celsius function calculates degrees Celsius from degreesFahrenheit. When the function is called from the ConvertTemp Sub procedure, avariable containing the argument value is passed to the function. The result of thecalculation is returned to the calling procedure and displayed in a message box.

    Sub ConvertTemp()temp = InputBox("Please enter the temperature in degrees F.", 1)MsgBox "The temperature is " & Celsius(temp) & " degrees C."

    End SubFunction Celsius(fDegrees)

    Celsius = (fDegrees - 32) * 5 / 9End Function

    Getting Data into and out of Procedures

    Each piece of data is passed into your procedures using an argument . Arguments serveas placeholders for the data you want to pass into your procedure. You can name yourarguments anything that is valid as a variable name. When you create a procedure

    using either the Sub statement or the Function statement, parentheses must beincluded after the name of the procedure. Any arguments are placed inside theseparentheses, separated by commas. For example, in the following example, fDegreesis a placeholder for the value being passed into the Celsius function for conversion:Function Celsius(fDegrees)

    Celsius = (fDegrees - 32) * 5 / 9End Function

    To get data out of a procedure, you must use a Function . Remember, a Functionprocedure can return a value; a Sub procedure can't.

    Using Sub and Function Procedures in Code

    A Function in your code must always be used on the right side of a variableassignment or in an expression. For example:Temp = Celsius(fDegrees)

    orMsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees."

  • 8/6/2019 VB Script Integratrd

    15/26

    To call a Sub procedure from another procedure, you can just type the name of theprocedure 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 anyarguments in parentheses.

    The following example shows two calls to the MyProc procedure. One uses the Callstatement 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'tused.

    VBScript Functions

    Date/Time Functions

    Function DescriptionCDate Converts a valid date and time expression to the variant of subtype

    DateDate Returns the current system dateDateAdd Returns a date to which a specified time interval has been addedDateDiff Returns the number of intervals between two datesDatePart Returns the specified part of a given dateDateSerial Returns the date for a specified year, month, and dayDateValue Returns a dateDay Returns a number that represents the day of the month (between 1

    and 31, inclusive)FormatDateTime Returns an expression formatted as a date or timeHour Returns a number that represents the hour of the day (between 0 and

    23, inclusive)IsDate Returns a Boolean value that indicates if the evaluated expression

    can be converted to a dateMinute Returns a number that represents the minute of the hour (between 0

    and 59, inclusive)Month Returns a number that represents the month of the year (between 1

    and 12, inclusive)MonthName Returns the name of a specified monthNow Returns the current system date and time

    http://www.w3schools.com/VBscript/func_cdate.asphttp://www.w3schools.com/VBscript/func_date.asphttp://www.w3schools.com/VBscript/func_dateadd.asphttp://www.w3schools.com/VBscript/func_datediff.asphttp://www.w3schools.com/VBscript/func_datepart.asphttp://www.w3schools.com/VBscript/func_dateserial.asphttp://www.w3schools.com/VBscript/func_datevalue.asphttp://www.w3schools.com/VBscript/func_day.asphttp://www.w3schools.com/VBscript/func_formatdatetime.asphttp://www.w3schools.com/VBscript/func_hour.asphttp://www.w3schools.com/VBscript/func_isdate.asphttp://www.w3schools.com/VBscript/func_minute.asphttp://www.w3schools.com/VBscript/func_month.asphttp://www.w3schools.com/VBscript/func_monthname.asphttp://www.w3schools.com/VBscript/func_now.asphttp://www.w3schools.com/VBscript/func_cdate.asphttp://www.w3schools.com/VBscript/func_date.asphttp://www.w3schools.com/VBscript/func_dateadd.asphttp://www.w3schools.com/VBscript/func_datediff.asphttp://www.w3schools.com/VBscript/func_datepart.asphttp://www.w3schools.com/VBscript/func_dateserial.asphttp://www.w3schools.com/VBscript/func_datevalue.asphttp://www.w3schools.com/VBscript/func_day.asphttp://www.w3schools.com/VBscript/func_formatdatetime.asphttp://www.w3schools.com/VBscript/func_hour.asphttp://www.w3schools.com/VBscript/func_isdate.asphttp://www.w3schools.com/VBscript/func_minute.asphttp://www.w3schools.com/VBscript/func_month.asphttp://www.w3schools.com/VBscript/func_monthname.asphttp://www.w3schools.com/VBscript/func_now.asp
  • 8/6/2019 VB Script Integratrd

    16/26

    Second Returns a number that represents the second of the minute (between0 and 59, inclusive)

    Time Returns the current system timeTimer Returns the number of seconds since 12:00 AM

    TimeSerial Returns the time for a specific hour, minute, and secondTimeValue Returns a timeWeekday Returns a number that represents the day of the week (between 1

    and 7, inclusive)WeekdayName Returns the weekday name of a specified day of the weekYear Returns a number that represents the year

    Conversion Functions

    Function DescriptionAsc Converts the first letter in a string to ANSI codeCBool Converts an expression to a variant of subtype BooleanCByte Converts an expression to a variant of subtype ByteCCur Converts an expression to a variant of subtype CurrencyCDate Converts a valid date and time expression to the variant of

    subtype DateCDbl Converts an expression to a variant of subtype Double

    Chr Converts the specified ANSI code to a characterCInt Converts an expression to a variant of subtype IntegerCLng Converts an expression to a variant of subtype LongCSng Converts an expression to a variant of subtype SingleCStr Converts an expression to a variant of subtype StringHex Returns the hexadecimal value of a specified numberOct Returns the octal value of a specified number

    Format Functions

    Function DescriptionFormatCurrency Returns an expression formatted as a currency valueFormatDateTime Returns an expression formatted as a date or timeFormatNumber Returns an expression formatted as a number

    http://www.w3schools.com/VBscript/func_second.asphttp://www.w3schools.com/VBscript/func_time.asphttp://www.w3schools.com/VBscript/func_timer.asphttp://www.w3schools.com/VBscript/func_timeserial.asphttp://www.w3schools.com/VBscript/func_timevalue.asphttp://www.w3schools.com/VBscript/func_weekday.asphttp://www.w3schools.com/VBscript/func_weekdayname.asphttp://www.w3schools.com/VBscript/func_year.asphttp://www.w3schools.com/VBscript/func_asc.asphttp://www.w3schools.com/VBscript/func_cbool.asphttp://www.w3schools.com/VBscript/func_cbyte.asphttp://www.w3schools.com/VBscript/func_ccur.asphttp://www.w3schools.com/VBscript/func_cdate.asphttp://www.w3schools.com/VBscript/func_cdbl.asphttp://www.w3schools.com/VBscript/func_chr.asphttp://www.w3schools.com/VBscript/func_cint.asphttp://www.w3schools.com/VBscript/func_clng.asphttp://www.w3schools.com/VBscript/func_csng.asphttp://www.w3schools.com/VBscript/func_cstr.asphttp://www.w3schools.com/VBscript/func_hex.asphttp://www.w3schools.com/VBscript/func_oct.asphttp://www.w3schools.com/VBscript/func_formatcurrency.asphttp://www.w3schools.com/VBscript/func_formatdatetime.asphttp://www.w3schools.com/VBscript/func_formatnumber.asphttp://www.w3schools.com/VBscript/func_second.asphttp://www.w3schools.com/VBscript/func_time.asphttp://www.w3schools.com/VBscript/func_timer.asphttp://www.w3schools.com/VBscript/func_timeserial.asphttp://www.w3schools.com/VBscript/func_timevalue.asphttp://www.w3schools.com/VBscript/func_weekday.asphttp://www.w3schools.com/VBscript/func_weekdayname.asphttp://www.w3schools.com/VBscript/func_year.asphttp://www.w3schools.com/VBscript/func_asc.asphttp://www.w3schools.com/VBscript/func_cbool.asphttp://www.w3schools.com/VBscript/func_cbyte.asphttp://www.w3schools.com/VBscript/func_ccur.asphttp://www.w3schools.com/VBscript/func_cdate.asphttp://www.w3schools.com/VBscript/func_cdbl.asphttp://www.w3schools.com/VBscript/func_chr.asphttp://www.w3schools.com/VBscript/func_cint.asphttp://www.w3schools.com/VBscript/func_clng.asphttp://www.w3schools.com/VBscript/func_csng.asphttp://www.w3schools.com/VBscript/func_cstr.asphttp://www.w3schools.com/VBscript/func_hex.asphttp://www.w3schools.com/VBscript/func_oct.asphttp://www.w3schools.com/VBscript/func_formatcurrency.asphttp://www.w3schools.com/VBscript/func_formatdatetime.asphttp://www.w3schools.com/VBscript/func_formatnumber.asp
  • 8/6/2019 VB Script Integratrd

    17/26

    FormatPercent Returns an expression formatted as a percentage

    Math Functions

    Function DescriptionAbs Returns the absolute value of a specified numberAtn Returns the arctangent of a specified numberCos Returns the cosine of a specified number (angle)Exp Returns e raised to a powerHex Returns the hexadecimal value of a specified numberInt Returns the integer part of a specified numberFix Returns the integer part of a specified number

    Log Returns the natural logarithm of a specified numberOct Returns the octal value of a specified numberRnd Returns a random number less than 1 but greater or equal to 0Sgn Returns an integer that indicates the sign of a specified numberSin Returns the sine of a specified number (angle)Sqr Returns the square root of a specified numberTan Returns the tangent of a specified number (angle)

    Array Functions

    Function DescriptionArray Returns a variant containing an arrayFilter Returns a zero-based array that contains a subset of a string array

    based on a filter criteriaIsArray Returns a Boolean value that indicates whether a specified

    variable is an arrayJoin Returns a string that consists of a number of substrings in an array

    LBound Returns the smallest subscript for the indicated dimension of anarraySplit Returns a zero-based, one-dimensional array that contains a

    specified number of substringsUBound Returns the largest subscript for the indicated dimension of an

    array

    http://www.w3schools.com/VBscript/func_formatpercent.asphttp://www.w3schools.com/VBscript/func_abs.asphttp://www.w3schools.com/VBscript/func_atn.asphttp://www.w3schools.com/VBscript/func_cos.asphttp://www.w3schools.com/VBscript/func_exp.asphttp://www.w3schools.com/VBscript/func_hex.asphttp://www.w3schools.com/VBscript/func_int.asphttp://www.w3schools.com/VBscript/func_fix.asphttp://www.w3schools.com/VBscript/func_log.asphttp://www.w3schools.com/VBscript/func_oct.asphttp://www.w3schools.com/VBscript/func_rnd.asphttp://www.w3schools.com/VBscript/func_sgn.asphttp://www.w3schools.com/VBscript/func_sin.asphttp://www.w3schools.com/VBscript/func_sqr.asphttp://www.w3schools.com/VBscript/func_tan.asphttp://www.w3schools.com/VBscript/func_array.asphttp://www.w3schools.com/VBscript/func_filter.asphttp://www.w3schools.com/VBscript/func_isarray.asphttp://www.w3schools.com/VBscript/func_join.asphttp://www.w3schools.com/VBscript/func_lbound.asphttp://www.w3schools.com/VBscript/func_split.asphttp://www.w3schools.com/VBscript/func_ubound.asphttp://www.w3schools.com/VBscript/func_formatpercent.asphttp://www.w3schools.com/VBscript/func_abs.asphttp://www.w3schools.com/VBscript/func_atn.asphttp://www.w3schools.com/VBscript/func_cos.asphttp://www.w3schools.com/VBscript/func_exp.asphttp://www.w3schools.com/VBscript/func_hex.asphttp://www.w3schools.com/VBscript/func_int.asphttp://www.w3schools.com/VBscript/func_fix.asphttp://www.w3schools.com/VBscript/func_log.asphttp://www.w3schools.com/VBscript/func_oct.asphttp://www.w3schools.com/VBscript/func_rnd.asphttp://www.w3schools.com/VBscript/func_sgn.asphttp://www.w3schools.com/VBscript/func_sin.asphttp://www.w3schools.com/VBscript/func_sqr.asphttp://www.w3schools.com/VBscript/func_tan.asphttp://www.w3schools.com/VBscript/func_array.asphttp://www.w3schools.com/VBscript/func_filter.asphttp://www.w3schools.com/VBscript/func_isarray.asphttp://www.w3schools.com/VBscript/func_join.asphttp://www.w3schools.com/VBscript/func_lbound.asphttp://www.w3schools.com/VBscript/func_split.asphttp://www.w3schools.com/VBscript/func_ubound.asp
  • 8/6/2019 VB Script Integratrd

    18/26

    String Functions

    Function DescriptionInStr Returns the position of the first occurrence of one string within

    another. The search begins at the first character of the stringInStrRev Returns the position of the first occurrence of one string within

    another. The search begins at the last character of the stringLCase Converts a specified string to lowercaseLeft Returns a specified number of characters from the left side of a

    stringLen Returns the number of characters in a stringLTrim Removes spaces on the left side of a stringRTrim Removes spaces on the right side of a string

    Trim Removes spaces on both the left and the right side of a stringMid Returns a specified number of characters from a stringReplace Replaces a specified part of a string with another string a specified

    number of timesRight Returns a specified number of characters from the right side of a

    stringSpace Returns a string that consists of a specified number of spacesStrComp Compares two strings and returns a value that represents the

    result of the comparisonString Returns a string that contains a repeating character of a specified

    lengthStrReverse Reverses a stringUCase Converts a specified string to uppercase

    Other Functions

    Function Description

    CreateObject Creates an object of a specified typeEval Evaluates an expression and returns the resultGetLocale Returns the current locale IDGetObject Returns a reference to an automation object from a fileGetRef Allows you to connect a VBScript procedure to a DHTML event on

    your pages

    http://www.w3schools.com/VBscript/func_instr.asphttp://www.w3schools.com/VBscript/func_instrrev.asphttp://www.w3schools.com/VBscript/func_lcase.asphttp://www.w3schools.com/VBscript/func_left.asphttp://www.w3schools.com/VBscript/func_len.asphttp://www.w3schools.com/VBscript/func_ltrim.asphttp://www.w3schools.com/VBscript/func_rtrim.asphttp://www.w3schools.com/VBscript/func_trim.asphttp://www.w3schools.com/VBscript/func_mid.asphttp://www.w3schools.com/VBscript/func_replace.asphttp://www.w3schools.com/VBscript/func_right.asphttp://www.w3schools.com/VBscript/func_space.asphttp://www.w3schools.com/VBscript/func_strcomp.asphttp://www.w3schools.com/VBscript/func_string.asphttp://www.w3schools.com/VBscript/func_strreverse.asphttp://www.w3schools.com/VBscript/func_ucase.asphttp://www.w3schools.com/VBscript/func_createobject.asphttp://www.w3schools.com/VBscript/func_eval.asphttp://www.w3schools.com/VBscript/func_getlocale.asphttp://www.w3schools.com/VBscript/func_getobject.asphttp://www.w3schools.com/VBscript/func_getref.asphttp://www.w3schools.com/VBscript/func_instr.asphttp://www.w3schools.com/VBscript/func_instrrev.asphttp://www.w3schools.com/VBscript/func_lcase.asphttp://www.w3schools.com/VBscript/func_left.asphttp://www.w3schools.com/VBscript/func_len.asphttp://www.w3schools.com/VBscript/func_ltrim.asphttp://www.w3schools.com/VBscript/func_rtrim.asphttp://www.w3schools.com/VBscript/func_trim.asphttp://www.w3schools.com/VBscript/func_mid.asphttp://www.w3schools.com/VBscript/func_replace.asphttp://www.w3schools.com/VBscript/func_right.asphttp://www.w3schools.com/VBscript/func_space.asphttp://www.w3schools.com/VBscript/func_strcomp.asphttp://www.w3schools.com/VBscript/func_string.asphttp://www.w3schools.com/VBscript/func_strreverse.asphttp://www.w3schools.com/VBscript/func_ucase.asphttp://www.w3schools.com/VBscript/func_createobject.asphttp://www.w3schools.com/VBscript/func_eval.asphttp://www.w3schools.com/VBscript/func_getlocale.asphttp://www.w3schools.com/VBscript/func_getobject.asphttp://www.w3schools.com/VBscript/func_getref.asp
  • 8/6/2019 VB Script Integratrd

    19/26

    InputBox Displays a dialog box, where the user can write some input and/orclick on a button, and returns the contents

    IsEmpty Returns a Boolean value that indicates whether a specifiedvariable has been initialized or not

    IsNull Returns a Boolean value that indicates whether a specifiedexpression contains no valid data (Null)IsNumeric Returns a Boolean value that indicates whether a specified

    expression can be evaluated as a numberIsObject Returns a Boolean value that indicates whether the specified

    expression is an automation objectLoadPicture Returns a picture object. Available only on 32-bit platformsMsgBox Displays a message box, waits for the user to click a button, and

    returns a value that indicates which button the user clicked

    RGB Returns a number that represents an RGB color valueRound Rounds a numberScriptEngine Returns the scripting language in useScriptEngineBuildVersion

    Returns the build version number of the scripting engine in use

    ScriptEngineMajorVersion

    Returns the major version number of the scripting engine in use

    ScriptEngineMinorVersion

    Returns the minor version number of the scripting engine in use

    SetLocale Sets the locale ID and returns the previous locale IDTypeName Returns the subtype of a specified variableVarType Returns a value that indicates the subtype of a specified variable

    Regular Expressions A regular expression is a pattern of text that consists of ordinary characters (forexample, letters a through z) and special characters, known as metacharacters . Thepattern describes one or more strings to match when searching a body of text. The

    http://www.w3schools.com/VBscript/func_inputbox.asphttp://www.w3schools.com/VBscript/func_isempty.asphttp://www.w3schools.com/VBscript/func_isnull.asphttp://www.w3schools.com/VBscript/func_isnumeric.asphttp://www.w3schools.com/VBscript/func_isobject.asphttp://www.w3schools.com/VBscript/func_loadpicture.asphttp://www.w3schools.com/VBscript/func_msgbox.asphttp://www.w3schools.com/VBscript/func_rgb.asphttp://www.w3schools.com/VBscript/func_round.asphttp://www.w3schools.com/VBscript/func_scriptengine.asphttp://www.w3schools.com/VBscript/func_scriptengine.asphttp://www.w3schools.com/VBscript/func_scriptengine.asphttp://www.w3schools.com/VBscript/func_scriptengine.asphttp://www.w3schools.com/VBscript/func_scriptengine.asphttp://www.w3schools.com/VBscript/func_scriptengine.asphttp://www.w3schools.com/VBscript/func_scriptengine.asphttp://www.w3schools.com/VBscript/func_setlocale.asphttp://www.w3schools.com/VBscript/func_typename.asphttp://www.w3schools.com/VBscript/func_vartype.asphttp://www.w3schools.com/VBscript/func_inputbox.asphttp://www.w3schools.com/VBscript/func_isempty.asphttp://www.w3schools.com/VBscript/func_isnull.asphttp://www.w3schools.com/VBscript/func_isnumeric.asphttp://www.w3schools.com/VBscript/func_isobject.asphttp://www.w3schools.com/VBscript/func_loadpicture.asphttp://www.w3schools.com/VBscript/func_msgbox.asphttp://www.w3schools.com/VBscript/func_rgb.asphttp://www.w3schools.com/VBscript/func_round.asphttp://www.w3schools.com/VBscript/func_scriptengine.asphttp://www.w3schools.com/VBscript/func_scriptengine.asphttp://www.w3schools.com/VBscript/func_scriptengine.asphttp://www.w3schools.com/VBscript/func_scriptengine.asphttp://www.w3schools.com/VBscript/func_scriptengine.asphttp://www.w3schools.com/VBscript/func_scriptengine.asphttp://www.w3schools.com/VBscript/func_scriptengine.asphttp://www.w3schools.com/VBscript/func_setlocale.asphttp://www.w3schools.com/VBscript/func_typename.asphttp://www.w3schools.com/VBscript/func_vartype.asp
  • 8/6/2019 VB Script Integratrd

    20/26

    regular expression serves as a template for matching a character pattern to the stringbeing searched.

    Metacharacters in Regular Expressions:

    . Matches any character excluding \nCharacter Sets[ xyz ] Matches any one of the enclosed characters.[ xyz ] A negative character set. Matches any character not enclosed.[a-z ] A range of characters. Matches any character in the specified range.

    \d matches a digit \D matches a non digit \w matches a word character ([a-zA-Z0-9_] \W matches a non word character \s matches a space character [\t\r\n\v\f ]

    \S matches a non space characterAnchors:Anchors are used to determine the position in a string.^ matches at the start of the string (or the position following the \n or \r if Multilineproperty is set).$ matches at the end of the string (or the position preceeding the \n or \r if Multilineproperty is set).

    \b matches at the word boundary. \B matches a non word boundary.(?= pattern ) Positive lookahead matches the search string at any point where a string

    matching pattern begins.Eg Win(?=98|95) matches Win98 but not Win.(?! pattern ) Negative lookahead matches the search string at any point where a stringnot matching pattern begins

    Quantifiers* Matches the preceding subexpression zero or more times.Eg. 'zo*' matches "z" and "zoo"+ Matches the preceding subexpression one or more times.Eg. 'zo+' matches "zo" and "zoo", but not "z".? Matches the preceding subexpression zero or one time.

    Eg. 'do(es)?' matches the "do" in "do" or "does".

    {n} n is a nonnegative integer. Matches exactly n times.Eg. 'o{2}' does not match the 'o' in "Bob," but matches the two o's in "food".{n,} n is a nonnegative integer. Matches at least n times.Eg. 'o{2,}' does not match the 'o' in "Bob" and matches all the o's in "foooood".{n,m} m and n are nonnegative integers, where n

  • 8/6/2019 VB Script Integratrd

    21/26

    Eg. 'o{1,3}' matches the first three o's in "fooooood". 'o{0,1}' is equivalent to 'o?'.

    *You cannot put a space between the comma and the numbers.* The non greedy versions of * and + are *? and +?.

    Alternation and GroupingAlternation allows use of the '|' character to allow a choice between two or morealternatives.Grouping is done using paranthesis ()This submatch can be referred to using the Submatches collection in VBScript.You can use '?:' before the regular expression pattern inside the parentheses toprevent the match from being saved for possible later use.

    Back referencesBack references to used to access matched text within the regular expression. To use

    a previous match use \num where num is the number of the matched group startingfrom 1.Eg. "\b([a-z]+|[1-9]+) \1\b

    Order of Precedence Once you have constructed a regular expression, it is evaluated much like anarithmetic expression, that is, it is evaluated from left to right and follows an orderof precedence.

    \ (), (?:), (?=), [] *, +, ?, {n}, {n,}, {n,m} ^, $, \ anymetacharacter |

    Methods in RegExp Object:

    Execute MethodExecutes a regular expression search against a specified string. The Execute method

    returns a Matches collection containing a Match object for each match found instring . Execute returns an empty Matches collection if no match is found.

    Replace Method

    The actual pattern for the text being replaced is set using the Pattern property of theRegExp object.The Replace method returns a copy of string1 with the text of RegExp.Patternreplaced with string2 . If no match is found, a copy of string1 is returned unchanged.Eg. Str1 = regEx.Replace(str1, replStr)regEx.Pattern = "(\S+)(\s+)(\S+)"regEx.Replace (abc def 123, "$3$2$1") ' Swap pairs of words.

  • 8/6/2019 VB Script Integratrd

    22/26

    Test MethodThe Test method returns True if a pattern match is found; False if no match is found.Eg. retVal = regEx.Test(strng) ' Execute the search test.

    Inbuilt Functions:

    *The functions described below are only few of among an exhaustive list. For the fulllist of functions refer to VBScript Language Reference.

    Array FunctionReturns a Variant containing an array.Eg. A = Array( 10,20,30) returns an array

    Eval FunctionEvaluates an expression and returns the result.Eg. Eval("Guess = RndNum")

    InputBox FunctionDisplays 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.Eg. Input = InputBox("Enter your name")

    Join FunctionReturns a string created by joining a number of substrings contained in an array.Join(list[, delimiter])The default delimiter is space.Eg. Join(myArray, ,) Returns a concantenated string of all the elements in thearray delimited by a comma .

    Left FunctionReturns a specified number of characters from the left side of a string.Left( string , length ) Eg. MyString = Left(abcd, 3) returns abc

    Right FunctionReturns a specified number of characters from the right side of a string.

    Right(string , length ) Eg. MyString = Left(abcd, 3) returns abc

    Replace FunctionReturns a string in which a specified substring has been replaced with anothersubstring a specified number of times.Eg. MyString = Replace( "XXpXXPXXp", "p", "Y") ' A binary comparison starting at the

    beginning of the string. Returns "XXYXXPXXY".

    Split Function

  • 8/6/2019 VB Script Integratrd

    23/26

    Returns a zero-based, one-dimensional array containing a specified number ofsubstrings.Split( expression[ , delimiter[ , count[ , compare]]] )Eg. MyArray = Split( MyString, "x", -1)

    String FunctionReturns a repeating character string of the length specified.Eg. MyString = String( 5, "*") ' Returns "*****".

    UCase FunctionReturns a string that has been converted to uppercase.Eg. MyWord = UCase("Hello World") ' Returns "HELLO WORLD".

    VBScript Keywords

    Empty : The Empty keyword is used to indicate an un initialized variable value.

    False : Boolean false.True : Boolean true.Nothing : The Nothing keyword in VBScript is used to disassociate an object variablefrom any actual object.Eg. Set MyObject = NothingNull: The Null keyword is used to indicate that a variable contains no valid data.

    VBScript ConstantsA number of useful constants you can use in your code are built into VBScript.

    Color Constants Defines eight basic colors that can be used in scripting. Date & Time Constants Defines date and time constants used by various date

    and time functions. Date Format Constants Defines constants used to format dates and times. MsgBox Constants Defines constants used in the MsgBox function to describe

    button visibility, labeling, behavior, and return values. String Constants Defines a variety of non-printable characters used in string

    manipulation.With StatementUsed to group a set of operations on a common object.Eg. With MyLabel

    .Height = 2000

    .Width = 2000

    End With

    Set StatementAssigns an object reference to a variable or property, or associates a procedurereference with an event.Eg. Set fso = CreateObject("Scripting.FileSystemObject")

    DataTable Object

  • 8/6/2019 VB Script Integratrd

    24/26

    QuickTest calls the values of a parameterized object from the DataTable using thefollowing syntax:

    Object_Hierarchy .Method DataTable ( parameterID , sheetID )

    Eg. Browser("Mercury Tours").Page("Find Flights").WebList("depart").SelectDataTable("Departure",dtGlobalSheet)

    Associated Methods in DataTable

    AddSheet Delete Sheet Export GetCurrentRow GetRowCount

    GetSheet GetSheetCount Import ImportSheet SetCurrentRow SetNextRow SetPrevRow

    FileSystemObject

    The FileSystemObject (FSO) object model can be used to manipulate Files and

    Folders.

    To program with the FileSystemObject (FSO) object model:

    1. Use the CreateObject method to create a FileSystemObject object.Eg. Dim fso Set fso = CreateObject("Scripting.FileSystemObject")

    2. Use the appropriate method on the newly created object.Eg. To create a new object, use either CreateTextFile or CreateFolder.Eg.To delete objects, use the DeleteFile and DeleteFolder methods of theFileSystemObject object, or the Delete method of the File and Folder objects. Youcan also copy and move files and folders, by using the appropriate methods.

    3. Access the object's properties or methods.

    Accessing Existing Drives, Files, and FoldersTo gain access to an existing drive, file, or folder, use the appropriate "get" method ofthe FileSystemObject object:

    GetDrive

  • 8/6/2019 VB Script Integratrd

    25/26

    GetFolder GetFile

    Eg. Set file = fso.GetFile("c:\test.txt") Once you have a handle to an object, you canaccess its properties.Eg. Response.Write "Folder name is: " & file.Name

    *Do not use the "get" methods for newly created objects, since the "create" functionsalready return a handle to that object.

    Working with Folders

    Creating a folder: FileSystemObject.CreateFolderDelete a folder: Folder.Delete or FileSystemObject.DeleteFolderMove a folder: Folder.Move or FileSystemObject.MoveFolderCopy a folder: Folder.Copy or FileSystemObject.CopyFolder

    Retrieve the name of a folder: Folder.NameFind out if a folder exists on a drive: FileSystemObject.FolderExistsGet an instance of an existing Folder object: FileSystemObject.GetFolderFind out the name of a folder's parent folder:

    FileSystemObject.GetParentFolderNameFind out the path of system folders: FileSystemObject.GetSpecialFolder

    Eg. Set fso = CreateObject("Scripting.FileSystemObject")Set fldr = fso.GetFolder("c:") ' Get Folder object.msgbox "Folder name is ." & fldr.Name ' Print folder name. fso.CreateFolder

    ("C:\tem") ' Create a new foldermsgbox fso.GetBaseName("c:\tem") ' Print folders base namefso.DeleteFolder ("C:\Bogus") ' Delete the newly created folder.

    Working with Files

    Creating Files1. Use the CreateTextFile method .

    Eg. Set f1 = fso.CreateTextFile("c:\testfile.txt", True)2. Use the OpenTextFile method of the FileSystemObject object with the ForWriting

    flag set.

    Eg. Const ForWriting = 2Set ts = fso.OpenTextFile("c:\test.txt", ForWriting, True)*For reading use 1 and for appending use 8 as the mode.3. Use the OpenAsTextStream method with the ForWriting flag set.

    Eg. fso.CreateTextFile ("c:\test1.txt")Set f1 = fso.GetFile("c:\test1.txt")Set ts = f1.OpenAsTextStream(ForWriting, True)

  • 8/6/2019 VB Script Integratrd

    26/26

    Adding Data to the File

    Write : Write data to an open text file without a trailing newline characterWriteLine: Write data to an open text file with a trailing newline character .WriteBlankLines : Write one or more blank lines to an open text file.

    *To close an open file, use the Close method of the TextStream object.Reading Files

    Read: Read a specified number of characters from a file.ReadLine: Read an entire line (up to, but not including, the newline character).ReadAll : Read the entire contents of a text file.

    *Use Skip(numOfBytes) or SkipLine methods to access particular portion of data.

    Moving, Copying, and Deleting Files

    To move a file: File.Move or FileSystemObject.MoveFileTo copy a file: File.Copy or FileSystemObject.CopyFileTo delete a file: File.Delete or FileSystemObject.DeleteFile

    Eg.Sub ManipFilesDim fso, f1, f2, sSet fso = CreateObject("Scripting.FileSystemObject")Set f1 = fso.CreateTextFile("c:\testfile.txt", True)f1.Write ("This is a test.") Write a line.

    f1.Close ' Close the file to writing.Set f2 = fso.GetFile("c:\testfile.txt") ' Get a handle to the file of C:\testfile.txt.f2.Move ("c:\tmp\testfile.txt") Move the file to \tmp directory.f2.Copy ("c:\temp\testfile.txt") ' Copy the file to \temp.Set f2 = fso.GetFile("c:\tmp\testfile.txt") ' Get handles to files' current location.Set f3 = fso.GetFile("c:\temp\testfile.txt")f2.Delete ' Delete the files.f3.DeleteEnd Sub