Excel VBA查找具体date

在Excel 2003中,我有一个sortingdate的列表,我想在特定的date之前find最后一个。 具体的date可能不会列出。 例如,2015年8月1日之前的最后date,但最近列出的date可能是20016年。我的报告中列出的date每周都有所不同。

下面是一些VBA,它会告诉你指定date之前的最后一个date:

Public Function getLastDate() As String Const columnNo As Byte = 1 Dim ws As Worksheet, lastRow As Integer, r As Integer Dim inputDate As String, searchDate As Date, latestDate As Date ' get date to search for inputDate = InputBox("Enter date value", "Date", Date) ' validate date entered If (inputDate = vbNullString) Then Exit Function On Error Resume Next searchDate = CDate(inputDate) If (Err.Number > 0) Then Exit Function On Error GoTo 0 Set ws = Worksheets("Sheet1") lastRow = ws.Cells(ws.Rows.Count, columnNo).End(xlUp).Row For r = 2 To lastRow ' check cell isn't empty If (ws.Cells(r, columnNo) = vbNullString) Then Exit For ' check that the cell date is before the input date If (DateValue(ws.Cells(r, columnNo)) > searchDate) Then Exit For ' remember the last date checked in case its the one I want latestDate = DateValue(ws.Cells(r, columnNo)) Next r ' return date value If (latestDate = 0) Then getLastDate = "No date found" Else getLastDate = latestDate End If End Function 

你说你的date列表是sorting的。 那么你将不需要VBA,但可以使用下面的简单公式。 在这里,我假设你已经提升了你的名单。

 =OFFSET($A$2,COUNTIF($A:$A,"<" & $D$4)-1,0,1,1) 

date位于A列,从第2行开始。指定date在D4。

截图:

在这里输入图像说明

如果您的列表按降序排列,则公式为:

 =OFFSET($A$2,COUNTIF($A:$A,">=" & $D$4),0,1,1)