Consulting

Results 1 to 5 of 5

Thread: Datediff in vba

  1. #1

    Datediff in vba

    I am using the following code in vba to find the difference between years :
    For j = 2 To 20
    If Range("H" & j).Value = "" Or Range("I" & j).Value = "" Then
        Range("J" & j).Value = ""
    Else
        Range("J" & j).Value = (DateDiff("yyyy", DateValue((Range("H" & j).Value)), DateValue((Range("i" & j).Value))) - 1)
        'ActiveSheet.Range("J" & j).Value = "=IF(OR(H2="",I2=""),"",DATEDIF(H2,I2,""y""))"
    End If
    Next j


    Suppose date in H2 = 06/08/2007 and date in I2 = 30/04/2008 Here worksheet datedif formula shows ?0? (Zero) years but VBA DATEDIFF is showing 1 year which is wrong.

    How can I use datediff function in VBA to get correct result? (Either of VBA DATEDIFF or Worksheet function DATEDIF, anyone is accepteable)


  2. #2
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    It gives me 0.
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

  3. #3
    At this line I have substracted 1
    Range("J" & j).Value = (DateDiff("yyyy", DateValue((Range("H" & j).Value)), DateValue((Range("i" & j).Value))) - 1)
    If you remove the -1 then wrong result will come.

    If you consider -1 then wrong result will come in this case
    Date in H2 :01/04/2008
    Date in I2 : 30/04/2011
    Worksheet Datedif gives 3 VBA Datediff will give 2

  4. #4
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    Oh yeah I see, It seems to take different years as a years difference.

    Try this

    [vba]

    Dim j
    For j = 2 To 20
    If Range("H" & j).Value = "" Or Range("I" & j).Value = "" Then
    Range("J" & j).Value = ""
    Else
    Range("J" & j).Value = Application.Evaluate("DateDif(" & Range("H" & j).Address & "," & Range("i" & j).Address & ", ""Y"")")
    'ActiveSheet.Range("J" & j).Value = "=IF(OR(H2="",I2=""),"",DATEDIF(H2,I2,""y""))"
    End If
    Next j
    [/vba]
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

  5. #5
    Thanks xld, its working correct.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •