Calculate time difference in VBA for Word - vba

I would like to calculate the time difference between 2 cells and the result showing in the 3rd cell of a MS WORD TABLE.
For instance, cell D2 showing 2pm and D1 showing 1pm and the difference in cell B2
Sub DetermineDuration()
Dim dtDuration As Date
dtDuration = DateDiff("h:mm:ss", D2, D1)
Range("B2").dtDuration
End Sub

Dates can be subtracted like numbers:
Sub DetermineDuration()
Range("B2") = Range("D2") - Range("D1")
End Sub
Make sure to format cell B2 as Time our you will just end up with a floating point number.

You can use the DateDiff function to return a specific interval type, like hours, minutes or seconds, without precision. It returns a regular number, not a time value. In the interval parameter you have to specify a valid interval value. You can learn about the function and see the valid interval values here MS Excel: How to use the DATEDIFF Function (VBA)
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week
h Hour
n Minute
s Second
As you can see, "h:mm:ss" is not a valid interval. You can use this format to get the seconds difference:
DateDiff("s", Range("D2"), Range("D1"))
If you want to get a time value, you can convert using the TimeSerial function.

Related

How can I find the time number of days between a given date, and the given date's first day of the year in VBA?

For example, the inputted date is 2001/01/21 the output must be 21 because 21 days passed since the inputted date's first day of the year.
Transform the date to a value and do the same for the "new" date? Do the same in Dev.mode newCelldate.Value - yearStartdate.Value?
Copy and paste the following to your VB Editor. Then, run the "TestNumberOfDays" procedure.
Function FirstDayOfTheGivenYear(pDate As Date)
'this will return first day of the given year
FirstDayOfTheGivenYear = 1 * (CDate(pDate) - DatePart("y", CDate(pDate) - 1))
End Function
Function YTDDays(pDate As Date) As Long
'this will find the day differences between two dates
YTDDays = DateDiff("d", FirstDayOfTheGivenYear(pDate), pDate) + 1
End Function
Sub TestNumberOfDays()
'change the date according to your need
MsgBox (YTDDays("2001/01/30"))
End Sub
Like this:
InputDate = #2001/01/21#
OrdinalDay = DatePart("y", InputDate)

How to subtract Time in Excel VBA?

How do I subtract Time in Excel VBA?
I tried to subtract these two values, but I'm getting this value "2.1527777777778E-02" instead. What does this mean?
Timein = 12/7/16 12:00:00 AM
Timeout = 12/7/16 12:30:00 AM
Here's a sample of my code. Thanks in advance.
Dim Total as Double
Dim Timein as Date
Dim Timeout as Date
Total = TimeValue(Timeout) - TimeValue(Timein)
'Result Total=2.1527777777778E-02
You can use the DateDiff Function to get the difference in year/days/seconds or whatever.
Here the example for minutes.
Dim Timein As Date
Dim Timeout As Date
Timein = "12/7/16 12:00:00 AM"
Timeout = "12/7/16 12:30:00 AM"
Debug.Print DateDiff("n", Timein, Timeout)
Output:
30
Interval Explanation
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week
h Hour
n Minute
s Second
What you have done is perfectly correct, as can be seen by the following code:
Sub test()
Dim Total As Double
Dim Timein As Date
Dim Timeout As Date
Timein = CDate(Range("A1").Value)
Timeout = CDate(Range("A2").Value)
Total = TimeValue(Timeout) - TimeValue(Timein)
Debug.Print Total
Debug.Print Format(Total, "hh:mm:ss")
Range("A3").NumberFormat = "hh:mm:ss"
Range("A3").Value = Total
Debug.Print "Number of hours = " & Total * 24
End Sub
As mentioned by vacip in a comment, Date/Time variables are stored in VBA in "days" so, for example, Now for me is the number 42867.7513310185.
2.1527777777778E-02 is using a method of displaying a value called Scientific Notation. In your case, it means 2.1527777777778 times 10 to the power of -2. Or you could think of the E-02 part as meaning shift the decimal point two places to the left (left because it's negative).
So: 0.021527777777778.
Excel treats time (both dates and times of day) as whole days so half a day (12 hours) would be represented as 0.5.
So the result itself represents the decimal fraction of an entire day, if you want this in minutes for example, you would multiply the value by 1440 (24hr x 60min make a day) which would give you 31mins.
In your example, you're finding the difference between 12:00 and 12:30 so you should actually be getting a result of 2.08333333333333E-02 which if multiplied by 1440 would give you 30mins.
Excel gives you tools to find the difference between two points in time though that take all that complex math(s) away - DateDiff and #holger has given you everything you need there to write your own code.
You have defined the total as double, which returns you number. you need to dim the total as date so that returns you a time.
Dim Total as Date
Dim Timein as Date
Dim Timeout as Date
Total = TimeValue(Timeout) - TimeValue(Timein)

Rounding Date and Time in VBA

How can I round off date and time in excel using VBA?
For example, the user selects the value from the calendar which is copied in Cell A6 = "08/25/2016 09:02:00"
I am pulling the data in 15 minutes interval so I want it to be A6 = "08/25/2016 09:00:00"
So if the user selects any date and time that is not in multiple of 15 minutes, it should go back to the previous 15 minute interval value and pull the data.
Pull out the minutes, floor the date portion to get rid of the time, then add it back by building it with TimeSerial:
Private Sub Example()
Dim foo As Date
foo = CDate("08/25/2016 09:02:00")
Dim minutes As Long
minutes = Minute(foo)
minutes = 15 * (minutes \ 15) 'Round down by 15 minute increments
foo = Int(foo) + TimeSerial(Hour(foo), minutes, 0)
Debug.Print foo
End Sub
Edit: Like #Pekka mentions, this can be done with a worksheet formula too - this is the equivalent to the code VBA above:
=INT(A6)+TIME(HOUR(A6),INT(MINUTE(A6) / 15) * 15, 0)
VBA is not necessary. This can be done directly in Excel. =FLOOR(A6,TIME(0,15,0)) will truncate a date time value to the previous 15 minute value.
Excel represents date values as a floating point value since an initial date (around 1900, depending on version) with the time as the fractional portion of the value.
You could, of course, use the same expression in VBA code in the same way.
As Jeeped comments, this is a more self-documenting alternative to the more direct expression =int(A6*24*4)/4/24 initially suggested.
A bit shorter version of the other answers
=MRound(A6, 1/96)
which in VBA can be
[a6] = [MRound(A6, 1/96)]
or to round down
[a6] = [Int(A6*96)/96]

Input month as an integer, output the final day of that month

I am trying to write an Excel VBA function that outputs the final day in a month in the format yyyy-mm-dd when given only the month number as an integer.
So for January, a 1 would be input and the output would be 2014-01-31.
I know how to reformat the date using Format(date(), "yyyy-mm-dd") and think I can calculate the last day using DateSerial but am not sure how to input an integer month number into the DateSerial function.
What is the best way to go about this?
Try:
Function: =TEXT(DATE(2014, A1 + 1, 1)-1,"yyyy-mm-dd")
VBA: DateSerial(Year, Month + 1, 1) - 1
This function finds the first day of the next month and then subtracts one day.
Paste into any cell except A1 and input your month in A1 to test.
As a formula, with your formatting, assuming the year is 2014 and your month number is in A1:
=EOMONTH(41639,A1)

How could I use vba to check if dates are the same?

I'm trying to write a code on cells that have both dates and times in them (Example: 1/29/14 9:15 AM). I'm trying to see if the date from 1 cell matches the date on another cell. How could I do that?
Example:
A1: 2/13/14 B1: 2/13/14 - This would return True
A2: 1/15/14 B2: 4/25/14 - This would return false
Any way I could achieve this?
Thanks
Excel stores dates as fractional numbers where the whole number represents the date and the fraction represents the time of day (e.g., 0.5 = noon). The whole number is the number of days since 1/1/1900. So Excel stores 1/3/1900 6:00 PM internally as 3.75.
As long as they are formatted as dates, you can compare them directly:
C1 formula: =(A1=B1)
C2 formula: =(A2=B2)
To ignore the time portion of the date, take the integer portion only:
C1 formula: =(INT(A1)=INT(B1))
C2 formula: =(INT(A2)=INT(B2))
There's no real need for VBA, but if you want to compare the dates in VBA, the same rules apply:
Sub CompareDates()
With ActiveSheet
.[C1] = (Int(.[A1]) = Int(.[B1]))
.[C2] = (Int(.[A2]) = Int(.[B2]))
End With
End Sub