简体   繁体   中英

How to calculate time difference (in second) in excel vba for different group of unique values?

I know this question appears often previously, but what I have is in the different case. I have some data about date and time which is for two groups. I want to know the duration for each group, but I dont know how to write it in the Excel VBA codes. Could you please help me to solve it? Here is my excel sheet. enter image description here The hard thing is that when in the same group it has changed to other date but when I try to substract the difference, it can be minus not positive. for example :

02.09.2017 19:00:00
03.09.2017 01:00:00

In this case I can't substract 01:00:00 - 19:00:00 because that would be minus, thus I have to consider the change of the date. How can I solve it if it is the case? Thank you very much for the help.

If your cells are formatted as data and time, you can use DateDiff function, with "n" as the interval (represnting the dif in seconds).

I've tested with your data:

A1 02.09.2017 19:00:00 
A2 03.09.2017 01:00:00

Code :

Option Explicit

Sub CalcSecond()

Dim NumofSec As Long

NumofSec = DateDiff("n", Range("A1").Value, Range("A2").Value)

MsgBox NumofSec

End Sub

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