Option Explicit
Sub Date_Finder()
Dim Wb As Workbook
Dim Ws As Worksheet
Dim LookVal, MaxDate, MinDate, CloseDate, x, y As Double
Dim LastRow, i As Long
Dim Rng, c As Range
Dim DateArray() As Variant
'You can change Workbook or Worksheet
'where value will be looked for
Set Wb = ActiveWorkbook
Set Ws = Wb.Worksheets("Date")
With Ws
'You can change column letter where match can be found
'and change 1 to 2 if you have a header
LastRow = .Range("B65536").End(xlUp).Row
Set Rng = .Range("B1:B" & LastRow)
'You can change reference to the cell which will be
'used to find the match
LookVal = CDbl(.Range("A1").Value)
End With
'Looking for Max and Min date within the renge
MaxDate = WorksheetFunction.Max(Rng)
MinDate = WorksheetFunction.Min(Rng)
'Declaring an Array
ReDim DateArray(1 To LastRow)
If LookVal < MaxDate Then
If LookVal > MinDate Then
For Each c In Rng
i = i + 1
'This will create an Array with differences
'beetween looked value and values within the range
DateArray(i) = Abs(DateDiff("d", CDbl(c), LookVal))
Next c
'This will give you 2 the closest values
CloseDate = WorksheetFunction.Min(DateArray())
x = LookVal + CloseDate
y = LookVal - CloseDate
'This will set up conditional formating to highlight all the
'cells with matching values
With Rng
.FormatConditions.Delete
.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:=x
'You can change colour index here
.FormatConditions(1).Interior.ColorIndex = 3
.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:=y
.FormatConditions(2).Interior.ColorIndex = 3
End With
Else
'This will set up conditional formating to highlight all the
'cells with matching values
With Rng
.FormatConditions.Delete
.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:=MinDate
.FormatConditions(1).Interior.ColorIndex = 3
End With
End If
Else
'This will set up conditional formating to highlight all the
'cells with matching values
With Rng
.FormatConditions.Delete
.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:=MaxDate
.FormatConditions(1).Interior.ColorIndex = 3
End With
End If
End Sub
|