Understanding Procedures in VBScript - Subs and Functions
(Page 2 of 5 )
VBScript provides two different procedural statements: Sub and Function. While both are basically the same, they do have one major difference. Functions can return a value upon execution while Subs can not.
Subs and Functions are often collectively, and interchangeably, referred to as “methods.”
Both Sub and Function statements are closed with an End statement. Either one may also have parameters, as you’ll see later in this article. Sub and Function blocks are also often grouped at the end of a script for convenience purposes. For now, let’s look at how to construct a Sub block.
Sub PrintMessage
WScript.Echo "Hello, World!"
End Sub
This simple PrintMessage subroutine performs a single task. It displays a message box with “Hello, World!” No matter how simple or complex, a subroutine is just a group of statements. In this case, any time I wanted to display the message box, I could simply call my subroutine.
PrintMessage
Sub PrintMessage
WScript.Echo "Hello, World!"
End Sub
I can call my subroutine by simply using its name. VBScript recognizes this as the name of a subroutine and processes the statements in that subroutine before continuing.
Call PrintMessage
Sub PrintMessage
WScript.Echo "Hello, World!"
End Sub
More appropriately, you can call a subroutine using the Call statement. In more complex scripts, this can add a level of readability to your script by making it easier to recognize a subroutine call. It is also used to discard the return value from any Function, as you’ll see later.
PrintMessage
Function PrintMessage
WScript.Echo("Hello, World!")
End Function
As I stated before, Subs and Functions are essentially the same thing. Here is my example again using a Function instead.
So what’s all this talk about returning values? Often, you may have a set of statements that retrieve or calculate some type of information that you would like to use in your script. You can use a function to get that information and return it. You can then capture that return value in a variable so that it can be used later in your script.
intBorn = 1979
strAge = CalculateAge
WScript.Echo "Mary was born in", intBorn
WScript.Echo "She is", strAge, "years old."
Function CalculateAge
intAge = Year(Date) - intBorn
CalculateAge = intAge
End Function
In this example, I’ve created a very simple function that calculates an age by subtracting a given year from today’s date. My function then returns that number. Notice the last line of my function. I’ve set the name of my function equal to the value that I would like to be returned.
The return value of a function is always of type Variant.
Now let’s take this example and see how we can further control it by using parameters.
Next: Using Parameters >>
More Windows Scripting Articles
More By Nilpo