tags:

views:

84

answers:

2

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
+4  A: 

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
astander
Will this also work on VBA? I tried it on VBA but it is not working. It can't recognize ParamArray
Kratz
The code above has the right idea, but won't compile as-is. 1) A `ParamArray` can't be declared `ByVal` and 2) it can only be declared as a `Variant` array. Therefore, the function declaration should be `Function Sum(ParamArray Vals() As Variant)`
Mike Spross
@ Mike Spross: It works based on the rules you stated. Thanks.@ astander: thanks for the heads up.
Kratz
@Mike Spross, @Katz, @astander I have taken the liberty of editing astander's answer to correct the syntax. Mike was quite right about the changes needed. (Also +1 to Arvo who has also suggested optional arguments)
MarkJ
+4  A: 

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.)

Arvo
+1 Your syntax is perfect
MarkJ