Excel:在用户定义的函数中传递数组?

时间:2009-12-04 15:44:23

标签: arrays excel vba parameters user-defined-functions

如何将数组作为MS Excel VBA中用户定义函数的参数传递?

最终我想测试一个给定日期(dateDay)是否在几个日期范围内(arrayVacation):

Function CB_IsInRangeArr(dateDay As Date, ParamArray arrayVacation() As Variant) As Boolean

    ' Test that the array is in the form of 2 columns and n rows / if not send back an error
    If (UBound(arrayVacation, 1) <> 2) Then
        CB_IsInRangeArr = CVErr(xlErrNA)
    Else
        CB_IsInRangeArr = TRUE
    End If
End Function

然而,在此阶段,该功能无法正常工作。它返回#VALUE!

2 个答案:

答案 0 :(得分:4)

好的,我添加了一个功能

Public Function CB_IsInRangeArr(c As Date, range As range) As Boolean
Dim iRow As Integer

    For iRow = 1 To range.Rows.Count
        Dim startDate As Date, endDate As Date
        startDate = range.Cells(iRow, 1)
        endDate = range.Cells(iRow, 2)
        If (startDate <= c And endDate >= c) Then
            CB_IsInRangeArr = True
            Exit Function
        End If
    Next iRow
End Function

这允许您添加日期范围和要检查日期的单元格。

然后单元格中的公式为

=CB_IsInRangeArr(C1,A1:B2)

c1是要检查的日期,a1:b2是日期范围。

请问我是否可以进一步提供帮助。

答案 1 :(得分:2)

Paramarray创建一个变体数组,每个元素都包含参数: 试试这样的事情


Function CB_IsInRangeArr(dateDay As Date, ParamArray arrayVacation() As Variant) As Variant

    Dim nParams As Long
    Dim vRangeValues As Variant
    Dim jParam As Long
    Dim j As Long

    nParams = UBound(arrayVacation) - LBound(arrayVacation) + 1
    If nParams &le 0 Then Exit Function
    On Error GoTo Fail

    For jParam = LBound(arrayVacation) To UBound(arrayVacation)

        vRangeValues = arrayVacation(jParam).Value

        For j = LBound(vRangeValues) To UBound(vRangeValues)
            If (vRangeValues(j, 1) &le dateDay And vRangeValues(j, 2) &ge dateDay) Then
                CB_IsInRangeArr = True
                Exit Function
            End If
        Next j

    Next jParam

    Exit Function
Fail:
    CB_IsInRangeArr = CVErr(xlErrNA)
End Function