VBScript - Session4.ppt

23
HP Global Soft Pvt Ltd

Transcript of VBScript - Session4.ppt

  • HP Global Soft Pvt Ltd

    Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.

  • AgendaRuntime ObjectsCreating ObjectsFileSystemObject LibraryFileSystemObject MethodsCreating a FolderCopying a FileCopying a FolderReading a Text FileWriting into Text FileVerify that File Exists or NotDelete a File and All Files in a FolderExamplesRead Excel FileJoin FunctionFormat Date and Time (IE Only)Hyper Link (IE Only)Q & A

    *

  • What are Runtime Objects?Runtime objects are labeled as runtime because they exists in a separate component , apart from core VBScript interpreter.

    These objects are not an official part of the VBScript language.

    These Runtime objects are going to be automatically available to you anywhere you would use VBScript.

    *

  • Creating ObjectsObjects are bit different than other data types , because objects must be created explicitly.

    When an object is instantiated , copy of that type of object is created in memory , with a pointer to the object stored in the variable you have declared for it.

    To create an object , you must declare a variable for it , and then use the Set command in conjunction with the CreateObject function.Ex:Option ExplicitDim objDict

    Set objDict = CreateObject(Scripting.Dictionary)Msgbox The dictionary object holds this many items: & _ objDict.CountThis code declares a variable to hold the object(objDict) , and then uses the set command and the CreateObject function to instantiate the object.The MsgBox line then displays the value of the objects count property.

    *

  • FileSystemObject Library Why FileSystemObject?Quite often scripts need the ability to create a file, read a file , find a file or folder , check for the existence of a certain drive , etc.

    The FileSystemObject is a kind of master object that serves as the access point for a family of the objects can use standard output values to output the property values of most objects.

    The FileSystemObject are intended for use with the windows Script host, ASP and other safe hosts.

    *

  • FileSystemObject Methods

    *

    MethodDescriptionCopyFileCopies one or more files from one location to anotherCopyFolderCopies one or more folders from one location to anotherCreateFolderCreates a new folderCreateTextFileCreates a text file and returns a TextStream object that can be used to read from, or write to the fileDeleteFileDeletes one or more specified filesDeleteFolderDeletes one or more specified foldersDriveExistsChecks if a specified drive existsFileExistsChecks if a specified file existsFolderExistsChecks if a specified folder existsGetDriveReturns a Drive object corresponding to the drive in a specified pathGetDriveNameReturns the drive name of a specified pathGetFileReturns a File object for a specified pathGetFileNameReturns the file name or folder name for the last component in a specified pathGetFolderReturns a Folder object for a specified pathMoveFileMoves one or more files from one location to anotherMoveFolderMoves one or more folders from one location to anotherOpenTextFileOpens a file and returns a TextStream object that can be used to access the file

  • Creating a FolderExample: Option Explicit

    Dim FSODim objFolder

    Set FSo=CreateObject(Scripting.fileSystemObject)Set objFolder = FSo.GetFolder(C:\)If Not FSO.FolderExists (C:\TestVBScriptFolder) Then objFolder.SubFolders.Add TestVBScriptFolderMsgBox The C:\TestVBScriptFolder folder was created successfully End If*

  • Copying a File Example 1 (Copying a Single File)

    Option ExplicitDim FSOSet FSO = CreateObject (Scripting.FileSystemObject)

    If FSO.FileExists(c:\Test_Input_file.txt) Then

    FSO.CopyFile c:\Test_Input_file.txt, c:\Test_Input_file_copy.txt, TrueEnd IF

    Example 2 : (Copying a Set of files)

    Option Explicit

    Dim objFSO

    Const OverwriteExisting = True

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    objFSO.CopyFile "C:\

  • Copy a Folder Example:Option Explicit

    Dim FSOSet FSO = CreateObject (Scripting.FileSystemObject)

    If FSO.FolderExists (C:\TestVBScriptFolder) ThenFSO.CopyFolder C:\TestVBScriptFolder ,C:\Program Files\,TrueMsgbox Success..End IF

    *

  • Reading a Text File Example:Dim fsoDim objStream

    Set fso =CreateObject("Scripting.FileSystemObject")Set objStream = fso.OpenTextfile("c:\test.txt")

    Do while not objStream.AtEndOfStream

    strline= objStream.ReadLine

    msgbox strline

    Loop

    *

  • Writing To Text File Example:Dim fsoDim objStreamconst file_name= "c:\test.txt"

    Set fso =CreateObject("Scripting.FileSystemObject")Set objStream =fso.CreateTextFile(file_name)

    With objStream .WriteLine Test Line 1.WriteLine Test Line 2.WriteLine Test Line 3End withMsgbox Successfully created & file_name*

  • Verifying that a File Exists Example:

    Option Explicit

    Dim objFSO, objFolder

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    If objFSO.FileExists("C:\test.txt") Then

    Msgbox "File Exists"

    Else

    Msgbox "File does not exist."

    End If*

  • Deleting a File and All Files in a FolderExample 1 (Deleting a File)

    Option ExplicitDim objFSO, objFolder

    Set objFSO = CreateObject("Scripting.FileSystemObject")objFSO.DeleteFile("C:\Test.txt")MsgBox "Success"

    Example 2 (Deleting All Files in a Folder)

    Option ExplicitDim objFSO, objFolder

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    If MsgBox ("Are you sure want to delete files", vbYesNo) = vbYes ThenobjFSO.DeleteFile("C:\KK\*.xls")Msgbox "Success"ElseMsgbox "Failed to delete.."End If*

  • Read Excel File*Option Explicit

    Call ReadExcel ("c:\book1.xls","Sheet1","A1","AQ100",False)

    Function ReadExcel( myXlsFile, mySheet, my1stCell, myLastCell, blnHeader )

    ' This function reads data from an Excel sheet without using MS-Office

    ' Arguments:' myXlsFile [string] The path and file name of the Excel file' mySheet [string] The name of the worksheet used (e.g. "Sheet1")' my1stCell [string] The index of the first cell to be read (e.g. "A1")' myLastCell [string] The index of the last cell to be read (e.g. AQ100")' blnHeader [boolean] True if the first row in the sheet is a header

    .Contd

  • Read Excel File*' Returns:' The values read from the Excel sheet are returned in a two-dimensional' array; the first dimension holds the columns, the second dimension holds' the rows read from the Excel sheet.

    Dim arrData( ), i, j Dim objExcel, objRS Dim strHeader, strRange, strResult

    'Const adOpenForwardOnly = 0 'Const adOpenKeyset = 1 'Const adOpenDynamic = 2 Const adOpenStatic = 3

    ' Define header parameter string for Excel object If blnHeader Then strHeader = "HDR=YES;" Else strHeader = "HDR=NO;" End If.Contd

  • Read Excel File*' Open the object for the Excel file Set objExcel = CreateObject( "ADODB.Connection" ) objExcel.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _ myXlsFile & ";Extended Properties=""Excel 8.0;" & _ strHeader & """"

    ' Open a recordset object for the sheet and range Set objRS = CreateObject( "ADODB.Recordset" ) strRange = mySheet & "$" & my1stCell & ":" & myLastCell objRS.Open "Select * from [" & strRange & "]", objExcel, adOpenStatic

    ' Read the data from the Excel sheet i = 0.Contd

  • Read Excel File*Do Until objRS.EOF ' Stop reading when an empty row is encountered in the Excel sheet If IsNull( objRS.Fields(0).Value ) Or Trim( objRS.Fields(0).Value ) = "" Then Exit Do

    ' Add a new row to the output array ReDim Preserve arrData( objRS.Fields.Count - 1, i )

    ' Copy the Excel sheet's row values to the array "row"

    For j = 0 To objRS.Fields.Count - 1 If IsNull( objRS.Fields(j).Value ) Then arrData( j, i ) = "" Else arrData( j, i ) = Trim( objRS.Fields(j).Value ) strResult = strResult & arrData( j, i ) & vbtab End If Next .Contd

  • Read Excel File*' Move to the next row objRS.MoveNext ' Increment the array "row" number i = i + 1 Loop

    ' Return the results ReadExcel = strResult msgbox ReadExcel

    ' Close the file and release the objects objRS.Close objExcel.Close Set objRS = Nothing Set objExcel = Nothing End Function

  • Join Function*The Join function returns a string that consists of a number of substrings in an array.Option Explicit

    Dim a(5),b

    a(0)="Saturday"a(1)="Sunday"a(2)="Monday"a(3)="Tuesday"a(4)="Wednesday

    b=Filter(a,"e")

    Msgbox (join(b,""))

  • Format Date and Time (IE Only)*

    document.write(FormatDateTime(date(),vbgeneraldate))document.write("")document.write(FormatDateTime(date(),vblongdate))document.write("")document.write(FormatDateTime(date(),vbshortdate))document.write("")document.write(FormatDateTime(now(),vblongtime))document.write("")document.write(FormatDateTime(now(),vbshorttime))

    Syntax for FormatDateTime: FormatDateTime(date,namedformat).

  • Hyperlink (IE Only)*

    document.write("EDS and HP Company!")

    This example demonstrates a link, when you click on the link it will take you to eds.com

  • HP Global Soft Pvt Ltd

    Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.

  • HP Global Soft Pvt Ltd

    Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.

    Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.*Copyright 2006 RelQ Software Pvt. Ltd. All rights reserved.