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
1

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, that's a lot of work for an optional argument, as the duplicate target points out you could use an Array() to pass the arguments or use null-checking inside the procedure. Ref Optional Arguments in VBScript

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.