Private Sub CommandButton1_Click()
Dim a As Variant, b As Variant, dTime As Variant, ky As Variant
Dim i&, j&, k&, x&, y&, nRow1&, nRow2&, nRow3&, nRow4, nRowy&
Dim dic As Object
Dim time1 As Double, time2 As Double, time3 As Double, time4 As Double
Dim stor1 As Double, stor2 As Double, stor3 As Double, stor4 As Double
Dim stmp1 As Double, stmp2 As Double, stmp3 As Double, stmp4 As Double
Dim nDate As Date
'timestamps per day, around 00.00, 06.00, 12.00 and around 18.00
stmp1 = TimeValue("00:00")
stmp2 = TimeValue("06:00")
stmp3 = TimeValue("12:00")
stmp4 = TimeValue("18:00")
'Initial cell
a = Range("A1:K" & Range("A" & Rows.Count).End(3).Row).Value
ReDim b(1 To UBound(a, 1), 1 To UBound(a, 2))
Set dic = CreateObject("Scripting.Dictionary")
For i = 2 To UBound(a, 1)
dTime = a(i, 1)
If IsDate(dTime) Then
nDate = DateSerial(Year(dTime), Month(dTime), Day(dTime))
time1 = TimeValue(dTime)
time2 = TimeValue(dTime)
time3 = TimeValue(dTime)
time4 = TimeValue(dTime)
If Not dic.exists(nDate) Then
nRow1 = i
nRow2 = i
nRow3 = i
nRow4 = i
y = y + 1
dic(nDate) = y & "|" & nRow1 & "|" & nRow2 & "|" & nRow3 & "|" & nRow4 & "|" & time1 & "|" & time2 & "|" & time3 & "|" & time4
Else
nRowy = Split(dic(nDate), "|")(0)
nRow1 = Split(dic(nDate), "|")(1)
nRow2 = Split(dic(nDate), "|")(2)
nRow3 = Split(dic(nDate), "|")(3)
nRow4 = Split(dic(nDate), "|")(4)
stor1 = Split(dic(nDate), "|")(5)
stor2 = Split(dic(nDate), "|")(6)
stor3 = Split(dic(nDate), "|")(7)
stor4 = Split(dic(nDate), "|")(8)
If Abs(time1 - stmp1) < Abs(stor1 - stmp1) Then
stor1 = time1
nRow1 = i
End If
If Abs(time2 - stmp2) < Abs(stor2 - stmp2) Then
stor2 = time2
nRow2 = i
End If
If Abs(time3 - stmp3) < Abs(stor3 - stmp3) Then
stor3 = time3
nRow3 = i
End If
If Abs(time4 - stmp4) < Abs(stor4 - stmp4) Then
stor4 = time4
nRow4 = i
End If
dic(nDate) = nRowy & "|" & nRow1 & "|" & nRow2 & "|" & nRow3 & "|" & nRow4 & "|" & stor1 & "|" & stor2 & "|" & stor3 & "|" & stor4
End If
End If
Next
For Each ky In dic.keys
nRowy = Split(dic(ky), "|")(0)
nRow1 = Split(dic(ky), "|")(1)
nRow2 = Split(dic(ky), "|")(2)
nRow3 = Split(dic(ky), "|")(3)
nRow4 = Split(dic(ky), "|")(4)
k = k + 1
For j = 1 To UBound(a, 2)
b(k, j) = a(nRow1, j)
b(k + 1, j) = a(nRow2, j)
b(k + 1, j) = a(nRow3, j)
b(k + 1, j) = a(nRow4, j)
Next
k = k + 1
Next
'Final cell
Range("M2").Resize(k, UBound(b, 2)).Value = b
End Sub