How to find the difference between dates in VBA

前端 未结 3 1617
一生所求
一生所求 2020-12-20 15:43

I am trying to find out the difference between the system date and the date stored in the worksheet. If the difference between them is > 30 days, the result is true, else th

相关标签:
3条回答
  • 2020-12-20 16:02

    I wonder why I rarely see people using the date functions.

    You can also use this:

    if DateDiff("d", date1, date2) > 30 then
    

    in this case, date1 would be CDate(Worksheets("dates").Cells(1,1)) and date2 would be sdate (either cast with CDate or dim'd as a date as Jeff said.

    "d" means we are getting the difference in days. Here are the intervals for years, months, etc. in VBA:

    yyyy - Year
    q - Quarter
    m - Month
    y - Day of year
    d - Day
    w - Weekday
    ww - Week
    h - Hour
    n - Minute
    s - Second
    
    0 讨论(0)
  • 2020-12-20 16:18

    Try this:

    if CDate(Worksheets("dates").Cells(1,1)) - sDate > 30 then
    
    0 讨论(0)
  • 2020-12-20 16:23

    sDate is a STRING, which is NOT a Real Date!

    Convert your string to a date, using either the CDate() function or the DateValue() function.

    However, there is a caveat in this kind of conversion. These conversion will handle the following structures:

    yyyy/mm/dd
    yyyy/m/d
    mm/dd/yyyy
    m/d/yyyy
    

    These will not be correctly converted

    dd/mm/yyyy
    d/m/yyyy
    

    And avoid using any 2-digit year.

    I would advise using the DateSerial() function for date conversion.

    So regarding your code, assuming that the values on yor sheet are actually dates (to be certain, simply select the column and change the Number Format to GENERAL. If they are real dates, each will display a PURE NUMBER. Remember to hit UNDO to get your Date Format back)

    Dim result As Boolean
    
    If Worksheets("dates").Cells(1, 1).Value - Date > 30 Then
         result = True
    Else
         result = False
    End If
    
    0 讨论(0)
提交回复
热议问题