26

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
Kratz
  • 766
  • 5
  • 10
  • 17

3 Answers3

25

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
MarkJ
  • 30,070
  • 5
  • 68
  • 111
Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
  • Will this also work on VBA? I tried it on VBA but it is not working. It can't recognize ParamArray – Kratz Apr 13 '10 at 14:41
  • 1
    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 Apr 13 '10 at 14:48
  • @ Mike Spross: It works based on the rules you stated. Thanks. @ astander: thanks for the heads up. – Kratz Apr 13 '10 at 14:55
  • 1
    @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 Apr 13 '10 at 16:11
12

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
  • 10,349
  • 1
  • 31
  • 34
4

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)
Q---ten
  • 2,168
  • 1
  • 13
  • 17