Friday, November 19, 2010

VBScript Code - Understanding simple class

Write the below code in a notepad and save it as a .vbs file. Either run it from command prompt or run it by double-clicking on it.

VBScript Code - Understanding simple class

Class Connection_Class

Private var_objConn

Public Property Get Connection()
  Set Connection = var_objConn
End Property

Public Property Set Connection(objConnection)
  Set var_objConn = objConnection
End Property

End Class

Dim objMyClass

Set objMyClass = New Connection_Class
Set Objectconn = Createobject("Excel.Application")
Set objMyClass.connection = Objectconn

objMyClass.connection.visible = True
Set objWorkbook = objMyClass.connection.Workbooks.Add()
objWorkbook.worksheets("Sheet1").Cells(1, 1).Value = "Testing a value"

If you want to see clearly how this code works, there is an easy way. Copy the whole code in a new test in QTP and insert a breakpoint at line 11 (Set objMyClass = New Connection_Class) and Run the test. when the test pauses at the breakpoint, just keep pressing F11 to see the flow.

For line (Set objMyClass.connection = Objectconn) it calls Property Set and for the next two lines it calls Property Get.