Variable number of arguments in VB

2019-01-23 12:09发布

问题:

How to create a function with variable number of arguments in visual basic? ex.

x =  Sum(1,2,3)
y =  Sum(1,2)

Function Sum('how to declare argument here')
'Is there any special argument manipulation inside function before it is usable?
End Function

回答1:

Have a look at Passing a Variable Number of Arguments

Function Sum(ParamArray Vals() As Variant)
    Dim intLoopIndex As Integer
    For intLoopIndex = 0 To  UBound(Vals)

    Next intLoopIndex

End Function


回答2:

Use optional arguments, like:

Function Sum(Optional X1 As Integer=0, Optional X2 As Integer=0)

or universally variable arguments syntax

Function Sum(ParamArray XArr() As Variant)

(I may have messed with some syntax elements - feel free to correct.)



回答3:

The answers here are great. In my application I required an arbitrarily long list of optional arguments after a required initial argument.

You can do this by simply adding the required arguments before the ParamArray entry.

For example:

Function Arithmetic(FuncType As String, ParamArray Terms() As Variant)


标签: vb6