4

I want to include a ParamArray in my function, but my efforts have failed so far.

Let's say I want to build a function to calculate mean for discrete distribution.

The function has the following form:

Function Dist_Discrete(X1, P1, X2, P2, X3, P3, etc.)

There are two solutions currently come to my mind:

  1. Using optional arguments multiple of times.

  2. Using ParamArray

The second one is preferred. But here is some problem when I try to define

Function Dist_Discrete(ParamArray XVal() As Variant, ParamArray Prob() As Variant)

And an error message comes up - "Compile error"

I can find a way to go around this by setting even as probability and odd as value. But I think this might be a good temporary solution

2
  • 4
    ParamArray can only be used for the last parameter of a parameter list, which implies you can only have one. Commented Aug 19, 2019 at 14:01
  • 4
    if more than one ParamArray were somehow allowed, there would be no way to guess where the first one ends and the second one starts Commented Aug 19, 2019 at 14:14

2 Answers 2

4

Your posted example shows the inputs as cells in a contiguous column like X1, X2. etc. If this is the case, the just use Range objects as the inputs:

Function Dist_Discrete(X as Range, P as Range) as Double

then in a worksheet cell:

=DistDiscrete(X1:X30, P1:P30)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I think you are right. I was overthinking and complicating the problem
4

ParamArray specifies that a procedure parameter takes an optional array of elements of the specified type. ParamArray can be used only on the last parameter of a parameter list. Thus 2 param arrays are not possible. (learn.microsoft.com)

However, you may think about a little trick in Excel. E.g. lets consider the following Function:

Function SumAndMultiply(valuesToSum(), valuesToMultiply()) as Double which has the idea to sum the values of the valuesToSum() array and to multiply the result with each of the valuesToMultiply().

In VBA, if the first one is presented as a range, then it would work quite nicely:

enter image description here

Public Function SumAndMultiply(valuesToSum As Range, _
        ParamArray valuesToMultiply() As Variant) As Double

    Dim myCell As Range
    Dim sum As Double
    For Each myCell In valuesToSum
        sum = sum + myCell
    Next myCell

    Dim param As Variant
    SumAndMultiply = sum
    For Each param In valuesToMultiply
        SumAndMultiply = SumAndMultiply * param
    Next

End Function

1 Comment

thank you so much. That's right. I was overthinking and complicating the problem :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.