Excel VBA查找特定日期

时间:2016-06-16 07:22:09

标签: excel excel-vba excel-2003 vba

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

2 个答案:

答案 0 :(得分:1)

以下是一些VBA会告诉您指定日期之前的最后日期:

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

答案 1 :(得分:0)

您说您的日期列表已排序。然后你不需要VBA,但可以使用下面的简单公式。在这里,我假设您对列表升序进行了排序。

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

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

截图:

enter image description here

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

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