MS Excel:查找一行混合内容的最早date

有谁知道如何在Microsoft Excel中获得最早的date。 在每一行中没有可预测的列数,并且除date之外还有值需要忽略的值。 这可以用Excel公式或VBA来完成。

有没有人有什么build议?

现在我正在使用这个快速和肮脏的VBA函数,但是当我加载新的input数据(大约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 

您必须记住Excel(以及许多其他Microsoft产品)将date存储为浮点数字:

  • 整数部分是自1900年1月1日以来经过的天数(例如:1相当于1/1/1900)
  • 小数部分是经过一天的“分数”(例如:0.5相当于中午12:00)

那么如何find一个最小或最大的date值的问题,然后混淆的事实,你可能有许多其他的数字在你的行。 所以你必须首先定义date的“有效排名”。 之后,一个简单的“数组公式”可以做到这一点:

例。 假设您的有效范围是2000年1月1日到2100年12月31日。那么您的有效“数量级别”是:

  • 1/1/2000相当于36526
  • 12/31/2100相当于73415

现在您可以编写该函数来跟踪此范围内的最小date值:

 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()函数不是“失败的安全”:它必须采取一个有效的expression式(文本)来检测它是否是一个date,这可能取决于格式。 也就是说,您可能更喜欢使用isDate(.cells(r,c).Text)' instead of .value , since the Value属性可能会返回一个双值或浮点值,可以评估为“不是date” 。