简体   繁体   中英

Date Comparison Issue VBA

I am trying to compare Dates in a vba script. I believe the main issue is my formatting however I am not sure how to solve it.

Sub Rem9()
Dim i As Long
Dim lr As Long
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
 wsName = ws.Name

 lr = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

  FirstDateRead = CDate("1, 1,2018") 'Initialize the first Day of the year as the last day

For i = 1 To lr
Debug.Print FirstDateRead
Debug.Print ws.Cells(i, 1).Value

 If FirstDateRead > ws.Cells(i, 1).Value Then
               ws.Cells(i, 3).Value = 121325

End If

Next i
End Sub

According to my output the First Date Read is never greater than the values I am pulling, Which it is for all cases. I have included here an example of the debug.print from the script I am running to show the date formats. Additionally I want to confirm the values I am drawing from are indeed datevaluse as when I run them through the IsDate() Function it returns True. 在此处输入图片说明

One other issue if that my date format for the value I call is swapping the year and day. Does anyone know how to solve that. When I use the format function it returns the date as. 在此处输入图片说明

Try using the DateDiff function instead:

Sub dateDifference()

    Dim d1 As Date, d2 As Date

    d1 = CDate("1, 2,2018")
    d2 = Range("A1").Value ' insert a date in A1 to test

    Debug.Print DateDiff("d", d1, d2) ' first parameter set to days

End Sub

Edit #1

Use Format to compare apples with apples, so to speak:

d2 = Format(Range("A1").Value, "dd/mm/yyyy")

Assuming the cells containing the dates are in text format, try wrapping the comparison value in a cDate:

If FirstDateRead > Cdate(ws.Cells(i, 1).Value) Then
    ws.Cells(i, 3).Value = 121325
End If

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM