简体   繁体   中英

How to Calculate time difference in difference format in Excel using VBA

I have 2 columns with dates in different format.

在此处输入图像描述

As you can see one column is in dd/mm/yyyy format and other is in mm/dd/yyyy format.

I want to find the time difference among the two. Also, one column is in Date Format and other is in General Format.

I wrote a function in VB to calculate the difference like this:

 Function caclulateDifference(pDate1 As Date, pDate2 As Date) As Long

   TestDates = DateDiff("d", pDate1, pDate2)

 End Function

And I Call this in Excel using =caclulateDifference(b2,a2) However,

pDate1 is coming as 10/15/19 11:38:38 AM, but pDate2 appears as 10/19/15 9:09:23 AM and then difference is coming as 0.

I want difference in day, hour and minutes. What am I doing wrong?

You are getting 0 because there are 0 days between those values, PLUS, you never assign the Function a value to return anything other than the default value for Long .

Try it like this:

 Function caclulateDifference(pDate1 As Date, pDate2 As Date) As Long

   caclulateDifference = DateDiff("d", pDate1, pDate2)

 End Function

You will still get 0, but in this example, that's what you are supposed to get. Change the function to this, and then look at your debug window to see that the dates are getting formatted properly:

Public Function caclulateDifference(pDate1 As Date, pDate2 As Date) As Long

   Debug.Print pDate1
   Debug.Print pDate2

   caclulateDifference = DateDiff("d", pDate1, pDate2)

 End Function

Then test it using date values that are on different days to get something other than 0.

Now if you want it in more detail than days as you say, you need to return a value other than Long (might have milliseconds in the values too) and use a different argument in your DateDiff like this:

Public Function caclulateDifference(pDate1 As Date, pDate2 As Date) As Double

   caclulateDifference = DateDiff("s", pDate1, pDate2)

End Function

Then convert the number of seconds into the number of days, hours, minutes, and seconds.

Convert seconds to days, hours, minutes, and seconds

If you dont want the order to matter, and always get a positive number, use Abs (absolute value) function as well, like this:

Public Function caclulateDifference(pDate1 As Date, pDate2 As Date) As Double

   caclulateDifference = Abs(DateDiff("s", pDate1, pDate2))

End Function

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