Part 3: QTP and VBScript | Writing your first program in VBScript
Before starting with the code intensive topics (such as working with conditional statements & loop constructs in VBScript) as part of the QTP Tutorials series, it would be a good idea to first touch upon the most basic stuff in VBScript, which is ‘Writing and executing your first program in VBScript’. This is important because once you are clear with this concept, you can write your own scripts and thus practice the different concepts that will be covered in the remaining articles of QTP VBScript Tutorials series.
Although you can use QTP to run VBScript code snippets, its not an absolute requirement that you have QTP installed in your system. This is because VBScript comes installed by default in all Windows machines since Windows 98. So all you need is a text editor (like notepad) to write & execute VBScript code.
Lets see how you can create and execute VBScript programs directly using a text editor and by using QTP. In this article, we would execute a very basic VBScript program which displays some text in a message box.
Executing VBScript code without QTP
You can follow the below mentioned steps to run a VBScript program without using QTP.
1) Open any text editor (We’ll be using Notepad for this example).
2) Write the following code in notepad window.
'Declare a variable Dim sMessage 'Assign a value to the variable sMessage = "This script is executed without using QTP" 'Display the text in a messagebox Msgbox sMessage
3) Save the file with a .vbs extension (like Demo1.vbs).
Make sure that the file is saved as SomeName.vbs only and not SomeName.vbs.txt. To verify this, open any folder and go to ‘Tools -> Folder Options’, then select View tab and uncheck ‘Hide extensions for known file types’ check box. Then verify that the file doesn’t contain .txt extension at the end.
4) After the file is saved, double-click on the file icon. This would display a message box as shown in the below figure.
Executing VBScript code using QTP
In addition to using the above mentioned steps to write your scripts in notepad, you can also write and execute your VBScript code through QTP. To do so –
1) Open a new test in QTP.
2) Copy the following code in QTP test.
'Declare a variable Dim sMessage 'Assign a value to the variable sMessage = "This script is written and executed using QTP" 'Display the text in a messagebox Msgbox sMessage
3) Save the test (if needed).
4) Run the code using QTP.
Once you run the code in QTP, you would see a message box as shown in the below figure.
This was all about running sample VBScript code snippets in your system – with and without using QTP. You can use the same approach to write much more complex scripts on your own. Before finishing this article, I have a query for you.. Can you think of any advantages/disadvantages of using notepad and QTP for writing & executing your VBScript code? Do let us know you thoughts on this using the comments section.