Subroutines - an example

To call a subroutine just type it’s name in your main script. As an example, consider a replacement for MsgBox that replaces the dialog title with your own fixed message. Here's the entire code:

Sub MainScript

ShowMsg("Hello") 

End Sub

 

Sub ShowMsg(msgstr)

MsgBox msgstr, 0, "My custom msgbox" 

End Sub

 

Note: MsgBox, the built-in VBScript function, takes up to 5 parameters, three of which are used in the command above: prompt, buttons (0 makes it display only an "OK" button) and title. (the text in the title bar of the MsgBox dialog).

What's the point? This is obviously a trivial example but even so, if you wanted all your message boxes to display with your own message in the dialog title, repeatedly writing out the longer form with "my customer msgbox" every time you wanted to use this function would become tedious. To push the point home, which is quicker to write and easier to maintain:

Example A (using a subroutine)

Sub MainScript

ShowMsg("Hello1") 

ShowMsg("Hello2") 

ShowMsg("Hello3") 

ShowMsg("Hello4") 

ShowMsg("Hello5") 

ShowMsg("Hello6") 

End Sub

 

Sub ShowMsg(msgstr)

MsgBox msgstr, 0, "My custom msgbox" 

End Sub

 

Example B (without using a subroutine)

Sub MainScript

MsgBox "Hello1", 0, "My custom msgbox" 

MsgBox "Hello2", 0, "My custom msgbox" 

MsgBox "Hello3", 0, "My custom msgbox" 

MsgBox "Hello4", 0, "My custom msgbox" 

MsgBox "Hello5", 0, "My custom msgbox" 

MsgBox "Hello6", 0, "My custom msgbox" 

MsgBox "Hello7", 0, "My custom msgbox" 

End Sub