Using ParamArray()

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ADezii
    Recognized Expert Expert
    • Apr 2006
    • 8834

    Using ParamArray()

    Generally, the number of Arguments in a Procedure Call must be the same as in the Procedure Specification. If a Procedure requires 3 Arguments in its Specification, when calling the Procedure you must pass exactly 3 Arguments which should be of the specific Data Type and in the correct order as defined by the Procedure itself. A simple case will illustrate this point:
    [CODE=vb]
    Public Function fCalculateInter est(curPrincipa l As Currency, sngRate As Single, lngTermInMonths As Long) As Currency
    fCalculateInter est = curPrincipal * sngRate * lngTermInMonths
    End Function
    [/CODE]
    To the fCalculateInter est() Function, you should pass a CURRENCY, SINGLE, and LONG value, and the Function will then return a CURRENCY Data Type.

    A typical call to this Function may look something like:
    [CODE=vb]
    Dim curInterest As Currency
    curInterest = fCalculateInter est(75000, .0675, 240)
    [/CODE]
    By using the ParamArray Keyword, you can specify that a Procedure will accept an arbitrary number of Arguments. Each Argument to a ParamArray Parameter can be of a different Data Type. The Parameter itself must be declared as an Array of Type Variant. When the call is made, each Argument supplied in the call becomes a corresponding element of the Variant Array. Again, a simple code segment will illustrate this point. Several calls will be made to the fAverageNumbers () Function, each with a varying number of Arguments, some even with invalid Arguments. The Function definition along with several calls and associated Outputs will be demonstrated:
    [CODE=vb]
    Public Function fAverageNumbers (ParamArray varNumbers())
    Dim varX, varY, intNumsToAverag e As Integer

    intNumsToAverag e = 0

    For Each varX In varNumbers
    If IsNumeric(varX) And Not IsNull(varNumbe rs) Then
    varY = varY + varX
    intNumsToAverag e = intNumsToAverag e + 1
    fAverageNumbers = varY / intNumsToAverag e
    Else
    End If
    Next
    End Function
    [/CODE]
    Sample Calls and Outputs:
    [CODE=text]
    Debug.Print fAverageNumbers (20, 80, 50) 'produces 50
    Debug.Print fAverageNumbers (2, 4, 8, 16, 32, 64, 128, 256, 512) 'produces 113.55555555555 6
    Debug.Print fAverageNumbers (98.765, 34.988, 1004.56) 'produces 379.43766666666 7
    Debug.Print fAverageNumbers (Null, "Number", 500, 100) 'produces 300
    Debug.Print fAverageNumbers (16) 'produces 16
    [/CODE]
    NOTE: In my humble opinion, the ParamArray() Statement is an extremely valuable and versatile programming tool which can be used whenever the number of Arguments to be passed to a Procedure, as well as their Data Types are not known.
Working...