用户定义的函数不起作用

时间:2016-07-18 13:45:50

标签: excel vba udf

我有这个udf,基本上我想得的是来自矢量(列)的最新日期,与其他列中的其他数据匹配,这里是代码:

Option Explicit
Public Function GetLastDate(Carrier As String, CarrierVector As Range, DateVector As Range) As Variant
    Dim TempRange(1 To 10) As Variant
    Dim i, j As Integer
    For i = 1 To DateVector.Rows.Count
        With Application.WorksheetFunction
            If .Text(CarrierVector.Item(i), "#") = Carrier And .IsError(.VLookup(DateVector.Item(i), TempRange, 1, False)) Then
                j = j + 1
                TempRange(j) = DateVector.Item(i)
            End If
        End With
    Next i
    GetLastDate = Application.WorksheetFunction.Max(TempRange)
End Function

在这种情况下,如果在CarrierVector上找到Carrier变量,则对应于该载波的Date将存储在TempRange阵列上(如果不重复),最后,它将返回lattest Date,但是这样不起作用,它只是在调用函数的单元格上返回一个错误,你能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

问题似乎与VLookUp电话有关。我不知道为什么会失败,但我也认为不建议在VBA中使用工作表函数,除非没有好的选择。

但在这种情况下,您可以使用Collection来跟踪您已经拥有的一组独特日期:

Public Function GetLastDate(Carrier As String, CarrierVector As Range, 
                            DateVector As Range) As Variant
    Dim TempRange As New Collection
    Dim i As Integer
    Dim found As Boolean
    Dim max As Date
    For i = 1 To DateVector.Rows.Count
        With Application.WorksheetFunction
            If .Text(CarrierVector.Item(i), "#") = Carrier Then
                On Error Resume Next
                    found = TempRange.Item(DateVector.Item(i) & "")
                On Error GoTo 0
                If Not found Then
                    TempRange.Add DateVector.Item(i), DateVector.Item(i) & ""
                    If DateVector.Item(i) > max Then max = DateVector.Item(i)
                End If
            End If
        End With
    Next i
    GetLastDate = max
End Function

但是,我不确定为什么你需要使用这个TempRange,因为你没有将它用于其他任何事情。你可以完全放弃它:

Public Function GetLastDate(Carrier As String, CarrierVector As Range,
                            DateVector As Range) As Variant
    Dim i As Integer
    Dim found As Boolean
    Dim max As Date
    For i = 1 To DateVector.Rows.Count
        With Application.WorksheetFunction
            If .Text(CarrierVector.Item(i), "#") = Carrier Then
                If DateVector.Item(i) > max Then max = DateVector.Item(i)
            End If
        End With
    Next i
    GetLastDate = max
End Function