OilEconomist
Active Member
- Joined
- Dec 26, 2016
- Messages
- 439
- Office Version
- 2019
- Platform
- Windows
Thanks in advance for your assistance. The following MS Excel VBA Function finds the nearest date to today (current date) from a list which will either be today, or some prior date or some future date. How would I modify the code to to eliminate it finding a prior date and only finding either the current date or the next nearest future date. Also, if the column is blank or has words, how to just skip that column?
Excel Formula:
Option Explicit
Sub DateNearestTest()
'Dimensioning
Dim j As Long
Dim RowNoStart As Long
Dim ColNo As Long
Dim ColNoStart As Long
Dim ColNoEnd As Long
Dim ShtNmSrc As String
Dim RowInputUse As String
Dim LoopRng As Range
Dim LoopCell As Range
Dim DateMatchNearest As Variant
'Code
ShtNmSrc = "Important.Dates"
RowNoStart = 8
ColNoStart = 1
ColNoEnd = 12
With Sheets(ShtNmSrc)
Set LoopRng = Range(Cells(RowNoStart, ColNoStart), Cells(RowNoStart, ColNoEnd))
RowInputUse = "Yes"
For Each LoopCell In LoopRng
ColNo = LoopCell.Column
'Function DateMatchNearestF(ShtNmSrc As String, RowNoStart As Long, RowInputUse As String, _
ColNoStart As Long, ColNoEnd As Long, ColInputUse As String) As Variant
DateMatchNearest = DateMatchNearestF(ShtNmSrc, RowNoStart, RowInputUse, ColNo)
Next LoopCell
End With
End Sub
Function DateMatchNearestF(ShtNmSrc As String, RowNoStart As Long, RowInputUse As String, _
ColNo As Long) As Variant
'Dimensioning
Dim RowEnd As Long
Dim iMaxDiff As Long
Dim d As Long
Dim b As Range
Dim RngSrchDate As Range
Dim fndDate As Variant
'_________________________________________________________________________________________________________
'Code to find set the search range
If RowInputUse = "Yes" Then
With Sheets(ShtNmSrc)
RowEnd = .Cells(Rows.Count, ColNo).End(xlUp).Row
End With
End If
Set RngSrchDate = Sheets(ShtNmSrc).Range(Cells(RowNoStart, ColNo), Cells(RowEnd, ColNo))
'_________________________________________________________________________________________________________
'Code to find the date
With Sheets(ShtNmSrc)
With RngSrchDate
iMaxDiff = Application.Min(Abs(Application.Max(.Cells) - Date), Abs(Date - Application.Min(.Cells)))
For d = 0 To iMaxDiff
If CBool(Application.CountIf(.Cells, Date + d)) Then
fndDate = Date + d
Exit For
ElseIf CBool(Application.CountIf(.Cells, Date - d)) Then
fndDate = Date - d
Exit For
End If
Next d
Set b = .Find(What:=fndDate, After:=Sheets(ShtNmSrc).Cells(RowNoStart, ColNo), LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
'do something with the closest date. I do NOT recommend using .Select for anything beyond demonstration purposes
DateMatchNearestF = b.Value
End With
End With
End Function