2

How to define a Function in VBS with Default Valued parameter?

I had tried many different ways, nothing seems working

Function Calculate(operator1 = 20, operator2 = 30)
 ' logic goes here
End Function
Function Calculate(Optional ByVal operator1 As Int = 20, Optional ByVal operator2 As Int = 30)
 ' logic goes here
End Function
darkmatter
  • 25
  • 3
  • As pointed out in [the duplicate target](https://stackoverflow.com/a/1888947/692942) you could use an `Array()` to pass the arguments or use null-checking inside the procedure. Ref [Optional Arguments in VBScript](http://www.4guysfromrolla.com/webtech/071801-1.shtml). – user692942 Oct 06 '20 at 10:51

1 Answers1

3

I don't think VBScript supports 'Optional'. So you might have create a custom class like so:

class CustomClass
    Dim operator1
    Dim operator2

    function Calculate
        'set default values here
        if IsEmpty(operator1) then operator1 = 20
        if IsEmpty(operator2) then operator2 = 30

        msgbox operator1
        msgbox operator2
    end function
end class

Dim myCustomClass : Set myCustomClass = new CustomClass

'override values here if required
myCustomClass.operator1 = 11
myCustomClass.operator2 = 12

myCustomClass.Calculate

Set myCustomClass = Nothing
Captain_Planet
  • 1,228
  • 1
  • 12
  • 28
  • Wow, that's a lot of work for an optional argument, as [the duplicate target](https://stackoverflow.com/a/1888947/692942) points out you could use an `Array()` to pass the arguments or use null-checking inside the procedure. Ref [Optional Arguments in VBScript](http://www.4guysfromrolla.com/webtech/071801-1.shtml) – user692942 Oct 06 '20 at 10:49