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