RonaldSchultz
Programmer
VBScript does not natively support optional function parameters, which can be a problem. Over the years, a number of workarounds have been proposed, but these workarounds tend to be a bit complex.
Some workarounds are detailed here: [URL unfurl="true"]http://www.advancedqtp.com/optional-parameters/[/url]
and here: [URL unfurl="true"]http://www.tek-tips.com/viewthread.cfm?qid=1329150[/url]
Fortunately, there is another partial workaround that does not appear to be widely known. This workaround does not support differing numbers of parameters, but it does support optional parameter values.
Using [tt]VarType()[/tt] in the function body, it is possible to test whether a value was supplied in the function call before any attempt is made to use that value.
For example:
[pre]function FunctionName(arg1, arg2)
dim var1
'test to see whether arg1 is supplied as a string
if VarType(arg1) <> 8 then
var1 = "default value"
else
var1 = arg1
end if
...
end function[/pre]
Thus, [tt]FunctionName[/tt] may be called with or without a 1st parameter value:
[pre]call FunctionName("val1", "val2")
call FunctionName( , "val2")[/pre]
In this example, the optional parameter is expected as a string (type value = 8). Missing parameter values have a type value of 10. A full list of type values may be found on Microsoft’s web site: [URL unfurl="true"]http://msdn.microsoft.com/en-us/library/3kfz157h%28v=vs.84%29.aspx[/url]
A limitation of this workaround is that it does not work for the last parameter in the list.
Some workarounds are detailed here: [URL unfurl="true"]http://www.advancedqtp.com/optional-parameters/[/url]
and here: [URL unfurl="true"]http://www.tek-tips.com/viewthread.cfm?qid=1329150[/url]
Fortunately, there is another partial workaround that does not appear to be widely known. This workaround does not support differing numbers of parameters, but it does support optional parameter values.
Using [tt]VarType()[/tt] in the function body, it is possible to test whether a value was supplied in the function call before any attempt is made to use that value.
For example:
[pre]function FunctionName(arg1, arg2)
dim var1
'test to see whether arg1 is supplied as a string
if VarType(arg1) <> 8 then
var1 = "default value"
else
var1 = arg1
end if
...
end function[/pre]
Thus, [tt]FunctionName[/tt] may be called with or without a 1st parameter value:
[pre]call FunctionName("val1", "val2")
call FunctionName( , "val2")[/pre]
In this example, the optional parameter is expected as a string (type value = 8). Missing parameter values have a type value of 10. A full list of type values may be found on Microsoft’s web site: [URL unfurl="true"]http://msdn.microsoft.com/en-us/library/3kfz157h%28v=vs.84%29.aspx[/url]
A limitation of this workaround is that it does not work for the last parameter in the list.