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

Return population for a City
If you have a list of cities in A2:A100, use Data, Geography. Then =A2.Population and copy down.

sulakvea

Well-known Member
Joined
Jul 2, 2008
Messages
994
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
 
Master Excel Bundle

Excel contains over 450 functions, with more added every year. That’s a huge number, so where should you start? Right here with this bundle.

Forum statistics

Threads
1,164,445
Messages
5,837,287
Members
430,493
Latest member
CPG2970

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
Top