2016-07-18 49 views
0

我有這個UDF,基本上我想要得到的是從向量(列)那場比賽與其他列的其他數據的最晚日期,這裏是代碼:用戶自定義功能不工作VBA

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變量,則與該Carrier相對應的Date將存儲在TempRange數組上(如果沒有重複該數據),最後它將返回Lattest Date,但這樣做不會不起作用,它只是從函數調用的單元格返回一個錯誤,你能幫我嗎?

+0

您是否在函數中放置了一個斷點,然後逐步查看錯誤原因可能是什麼?如果沒有,這可能會幫助你回答你自己的問題。 –

+0

發生了什麼不正確的錯誤?另外,你有沒有想過使用字典和.exists函數而不是vlookup。 –

+0

它只是返回一個'#VALUE!'錯誤,並且在vba中(即時窗口),我試着用這行'GetLastDate(「53421」,AF1:AF1290,L1:L1290)''但是然後說「Expected list or separator」 「 – Jey

回答

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 
+0

第一個UDF是我想達到的,非常感謝你 – Jey