Sunday, November 8, 2009

Class concept in VBScript

In VB, Classes can be created using Class Module. Basic Module files are used to have user-defined procedures and variables. Many of the VB Scripts are designed by structure programming.

Using VBScript, one can apply OOPs based scripting also. Initalizing code should be added in Class_Initialize procedure. Similarly terminating code should be added into Class_Terminate procedure. Below I've given a sample VBS code for class implementation.

Sample code from Net: VBScript Class to Send Mail With CDOSYS
Sample VBS code for CLASS implementation

'' UtilClass.vbs ' Purpose: To illustrate Class concept in VBScript Class StringLib Private Sub Class_Initialize ' Class initialization MsgBox "Initializing StringLib class" End Sub Private Sub Class_Terminate ' Class termination -end of life MsgBox "Terminating StringLib class" End Sub ' Purpose : Checks the given file is avialable or not. Function FileExists(strPathName) Dim ObjFSO Set ObjFSO = CreateObject("Scripting.FileSystemObject") If ObjFSO.FileExists(strPathName) = False Then FileExists = -1 Else FileExists = 0 End If Set ObjFSO = Nothing End Function ' Purpose : To replace {dot} with {index}{dot} in the file name. Function ReplaceFileName(sFileName, iMySheetIndex) Dim RepChar, SearchChar SearchChar = "." ' Search for ".". RepChar = CStr(iMySheetIndex) & SearchChar ReplaceFileName = Replace(sFileName, SearchChar, RepChar) End Function End Class 'Using StringLib class Dim sText Dim sReplaced Set libStr = New StringLib sReplaced= libStr.ReplaceFileName ("c:\mytests.xls", 5) MsgBox "Replaced Text: " & sReplaced Set libStr = Nothing