2013-04-01 39 views
0

有誰知道如何獲取Microsoft Excel中行的最早日期。每行不存在可預測的列數,並且除日期之外還有值需要忽略的值。它可以用Excel公式或VBA完成。MS Excel:查找混合內容行中的最早日期

有沒有人有任何建議?

現在我用這個快速和骯髒的VBA函數,但是當我加載新的輸入數據(大約200行100列)一個消息框想出說,Excel沒有足夠的資源來處理我的變化。

' returns smallest date on row 
Public Function getSmallestDateFromRow(r As Integer, sheetName As String) As Date 
    Dim toReturn As Date 
    Dim rng As Range 
    Dim scanToColumn As Integer 
    Dim c As Integer 
    Dim tmp As Variant 

    Set rng = Sheets(sheetName).Cells.Find("*", [a1], , , xlByColumns, xlPrevious) 'is this inefficient? 
    scanToColumn = rng.Column 
    toReturn = #12/12/2100# 

    For c = 1 To scanToColumn 
     tmp = Sheets(sheetName).Cells(r, c).Value 
     If (IsDate(tmp)) Then 
      If (toReturn = Null) Then 
       toReturn = tmp 
      ElseIf (toReturn > tmp) Then 
       toReturn = tmp 
      End If 
     End If 
    Next c 

    If (toReturn = #12/12/2100#) Then 
     toReturn = 0 
    End If 

    getSmallestDateFromRow = toReturn 
End Function 
+0

這是一個Worksheet函數/ UDF嗎?或另一個宏調用的函數? – NickSlash

回答

2

你要記住,Excel中(和許多其他Microsoft產品)店日期爲浮點數:

  • 整數部分是自1900年1月1日經過的天數(例如, :圖1是等效於1/1/1900)
  • 小數部分是經過一天的「分數」(例如:0.5等同於下午12時)

如何找到一個問題最小o r的最大日期值會因爲您的行中可能有許多其他數字而被混淆。所以你必須首先定義日期的「有效排名」。之後,一個簡單的「陣列公式」可以做到這一點:

示例。比方說,你的有效範圍是2000年1月1日和12月31日,2100年那麼您的有效「數量排名」之間是:

  • 1/1/2000相當於36526
  • 2100年12月31日就相當於73415

現在你可以寫函數跟蹤此範圍內的最小日期值:

function trackMinimum(rowRange as range) as date 
    on error resume next 
    dim j as integer, minValue as date 
    dim t0 as double, t1 as double 
    dim ans as date 

    t0 = cdbl(dateserial(2000,1,1)) 
    t1 = cdbl(dateserial(2100,12,31)) 
    ans = 0 
    for j = 1 to rowRange.columns.count 
     if ans = 0 then ' You need to store the first valid value 
      if rowRange.cells(1,j).value >= t0 and rowRange.cells(1,j) <= t1 then 
       ans = rowRange.cells(1,j).value 
      end if 
     else 
      if (rowRange.cells(1,j).value >= t0 and rowRange.cells(1,j) <= t1) _ 
       and rowRange.cells.value < ans then 
       ans = rowRange.cells(1,j).value 
      end if 
     end if 
    next j 
    trackMinimum = ans 
end function 

當然,我假設rowRange參數是單行範圍。

希望這有助於你


順便說一句,在isDate()功能不是「故障安全」:它必須採取有效的表達式(文字)來檢測,如果它是一個日期或不是,那可能取決於格式。也就是說,您可能更願意使用isDate(.cells(r,c).Text)' instead of。值, since the Value屬性可能返回可以評估爲「不是日期」的雙精度值或浮點值。

+0

+1但沒有數組公式? –

+0

這不是一個數組公式......這是不需要的。當然,這個功能需要在每一行上「複製」。或者另一個函數或子可以對給定範圍內的每一行評估此公式 – Barranka