Optional Arguments in VBScript
By Francis Chau
Introduction:
A frequently asked question about VBScript is "How can I make an argument of a Function or Sub
optional?" and matter of factly, it's been answered on ASPFAQs.com at
http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=42.
The answer to this question? VBScript does not support optional arguments, however, JScript does
and the FAQ shows an example of this in JScript.
To circumvent this VBScript limitation, I will show you a technique that can be used to simulate optional arguments in VBScript that I call the Array-based approach. I'll also demonstrate the more widely accepted NULL-checking approach.
Using the Array-Based Approach
To see how to use the array-based approach for creating subroutines with optional arguments,
let's start by an example subroutine:
|
Notice in the subroutine declaration, we've only defined one argument, rArgs:
Sub mySubRoutine(rArgs)
|
The argument rArgs will be an array of values we would like to pass into our
subroutine.
The next few lines declare our local variables and initializes them to default values (empty
strings, in this case).
Next, we use the UBound() function to determine the number of arguments passed.
Then assign the array elements to the local variables:
|
Since the array is zero-based, our first Case branch assigns the first element to
our v1 variable. As we need to add more arguments to our function, we can easily
add more Case branches.
We conclude our subroutine by printing out the values of our local variables.
To call this subroutine we need to create an array of the size based on the number of arguments we wish to pass into the function, and then populate this array with the values we wish to pass to the function. Finally, we pass along the created array as the single argument to the function:
|
Notice that you can also use the Array constructor syntax like so:
'Call the subroutine with three arguments
|
Now that we have a way to pass only the arguments we choose using the array-based method, let's take a look at another approach at optional arguments: the NULL-checking approach, which we'll examine in Part 2.




