Function to find closest date to target with Hlookup

SakiSam

New Member
Joined
Jul 25, 2014
Messages
20
I am having trouble searching a range containing workday dates for the closest one to the target.
Ie. Jan 26, 2014 is on a Sunday, if this is the start date of a project I want the function to output Jan 24,2014. (This function is triggered by another sub, so I'm not really using it to output to the spreadsheet right away.)

Anyway, I've developed the following code.

Code:
Function tmep(dtlookup As Date, rngHdrDt As Range, startDt As Boolean) As Date

On Error GoTo errDtNtFnd
tmep = Application.WorksheetFunction.HLookup(dtlookup, rngHdrDt, 1, False)
On Error GoTo 0


Exit Function


errDtNtFnd:
If startDt Then
    dtlookup = DateAdd("d", -1, dtlookup)
Else: dtlookup = DateAdd("d", 1, dtlookup)
End If
Resume


End Function

To test the function I've inputted the following in the immediate window.

Code:
sheet4.tmep(#1/26/2014#,sheets("Report").Range("D6:ACF8"),true)

The range looks like the following except that the cells content are rotated 90 degrees and is three rows tall for the reports visual output:
1/17/20141/20/20141/21/20141/22/20141/23/20141/24/20141/27/20141/28/20141/29/2014

<tbody>
</tbody>

The result thus far is that the hlookup is not finding the 24th and continues to rollback the dtlookup. If I change the 24th to a text field type and the dtlookup to a string type(currently it is a short date type), the function locates the cell. However this creates a lot of problems for the sub that will use this function. So I'd like to maintain everything as a date format.



Any thoughts and comments are greatly appreciated.
 

Excel Facts

How to show all formulas in Excel?
Press Ctrl+` to show all formulas. Press it again to toggle back to numbers. The grave accent is often under the tilde on US keyboards.

Forum statistics

Threads
1,214,915
Messages
6,122,214
Members
449,074
Latest member
cancansova

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