2009-12-04 36 views
1

如何在MS Excel VBA中將數組作爲參數傳遞給用戶定義的函數?Excel:在用戶定義的函數中傳遞數組?

最後,我想測試,如果某一特定日期(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!

回答

4

OK,我增加了一個功能

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的日期範圍。

請問我是否可以進一步協助。

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 
相關問題