简体   繁体   English

在VBA Excel中处理时间时得到错误的值

[英]getting wrong value when dealing with time in vba excel

I'm trying to do some calculations on my excel sheet where I'm using macros , i'm dealing with time values. 我正在尝试在使用宏的excel工作表上进行一些计算,我正在处理时间值。

 h2 = rg.Cells(i, 5) 'time value
 h1 = rg.Cells(i, 4) 'time value
 h3 = (TimeValue("23:59") - h1) + (h2 - TimeValue("23:59"))

the problem is for instance when h1="20:00" and h2="07:55" h3 should be 11:55 but it gives 12:05 问题是,例如,当h1="20:00"h2="07:55" h3应该是11:55却给出12:05

BTW H1 is entrance time and H2 is time out so h2 is in the next day and i'm trying to calculate the deference of time. 顺便说一句, H1是进入时间, H2是超时,所以h2在第二天,我正在尝试计算时间差。

在此处输入图片说明

regards 问候

Because H2, as you point out, is a day after H1, you need to factor that in to your calculation. 正如您指出的那样,由于H2是H1的第二天,因此您需要将其纳入计算。

So to calculate the difference between H1 and H2, 24 hours should be added to H2 first. 因此,要计算H1和H2之间的差异,应首先将24小时添加到H2中。

  h2  +  1dy
07:55 + 24:00 = 31:55

                  v
                         -h1
                31:55 - 20:00 = 11:55

A single day presented as time is 1 - as time is measured as a decimal fraction of a day. 表示为时间的一天是1因为时间是以一天的小数部分表示的。

So among many other ways of doing it, to get the above, your formula should be: 因此,除其他外,要达到上述目的,您的公式应为:

h3 = (h2 + 1) - h1

In fact the correct answer is minus 11:05:00 but Excel doesn't handle negative time. 实际上,正确的答案是 11:05:00,但Excel不能处理负时间。 Adding one day to minus 11:05::00 equals positive 12:05:00. 负11:05 :: 00加上一天等于正数12:05:00。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM