finding the closest matching date in a range

dinotom

Active Member
Joined
Aug 2, 2009
Messages
357
Hello,

What is the fastest way to search a column of dates to find the closest date to a date passed as a parameter to the routine?

I am doing it by looping thru each cell in the range but Im sure there is a faster way
 

Excel Facts

How to fill five years of quarters?
Type 1Q-2023 in a cell. Grab the fill handle and drag down or right. After 4Q-2023, Excel will jump to 1Q-2024. Dash can be any character.
and if sorting the data is an option - here it is

replace DateVal = 25 line with whatever procedure you use to pass the value along. DateVal is that number (date in your case) that you wanna find the closest match for.
assumes data sits in Col A1:A1000

Rich (BB code):
Sub FindClosestMatch()

DateVal = 25

Range("A1:A1000").Sort Key1:=Range("A1"), Order1:=xlDescending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
MinVal = Cells(Application.WorksheetFunction.Match(DateVal, Range("A1:A1000"), -1), 1)

Range("A1:A1000").Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
MaxVal = Cells(Application.WorksheetFunction.Match(DateVal, Range("A1:A1000"), 1), 1)

If MinVal - DateVal > DateVal - MaxVal Then
 FinalVal = MaxVal
Else
 FinalVal = MinVal
End If
MsgBox (FinalVal)

End Sub
 
Upvote 0

Forum statistics

Threads
1,214,631
Messages
6,120,640
Members
448,974
Latest member
DumbFinanceBro

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top