简体   繁体   English

VBA宏-从日期和时间Excel单元格中提取时间-VBA

[英]VBA macro - extract time from date & time excel cell - VBA

I have to columns B and C which are containing data under the format mm/dd/yyyy hh:mm - which represents the start (column B) and the end dates (column C) of some meetings. 我必须在B和C列中包含以下格式的数据: mm/dd/yyyy hh:mm它表示某些会议的开始(B列)和结束日期(C列)。

I'm trying to create a VBA macro that can extract from both of the columns only the time under the format hh:mm and then calculate the difference between the two timings in order to find out the duration of each meeting (the result will be displayed on column D). 我正在尝试创建一个VBA宏,该宏只能以hh:mm格式从两个列中提取时间,然后计算两个时间之间的时差,以便找出每次会议的持续时间(结果将是显示在D列)。

Can you please advised what can be done into here? 您能建议在这里做什么吗?

In column D use the formula 在D列中使用公式

=(C:C-B:B)*24

to get the difference in hours. 得到小时的差异。


Or instead just use the below formula in column D 或者,只需在D列中使用以下公式

=C:C-B:B

and format column D as time to get the difference in a format like hh:mm 并将D列格式化为时间,以hh:mm类的格式获取差异


you can add this formula to a desired range with VBA if necessary like 您可以根据需要使用VBA将此公式添加到所需范围,例如

With Worksheets("MySheet").Range("D1:D5").Formula = "=(C:C-B:B)*24"

or time formatted like 或时间格式如

With Worksheets("MySheet").Range("D1:D5")
    .Formula = "=C:C-B:B"
    .NumberFormat = "hh:mm"
End With

Give this a try: 试试看:

Sub difff()
    Dim i As Long, N As Long

    N = Cells(Rows.Count, "B").End(xlUp).Row
    For i = 1 To N
        Cells(i, "D") = Cells(i, "C") - Cells(i, "B")
    Next i

    Range("D:D").NumberFormat = "hh:mm"
End Sub

在此处输入图片说明

With 19/06/2017 13:30:00 in A1 and 20/06/2017 13:39:00 in A2 . A1 19/06/2017 13:30:00和在A2 20/06/2017 13:39:00
The formula =A2-A1 given the custom number format of [h]:mm:ss returns 24:09:00 . 给定[h]:mm:ss的自定义数字格式的公式=A2-A1返回24:09:00
The square brackets around the h tell Excel to show times over 24 hours. h周围的方括号告诉Excel显示超过24小时的时间。
Without the square brackets it will show the time as 00:09:00 . 如果没有方括号,则时间将显示为00:09:00 This is because it is calculating as 1 day and 9 minutes, but is not showing the count of days. 这是因为它计算为1天9分钟,但未显示天数。

To get just the time from a date you can either just format as a time which will keep the dart part of your date/time but display just the time. 要仅获取日期中的时间,您可以将其格式化为时间,以保留日期/时间中的飞镖部分,但仅显示时间。
Or, you can remove the integer of the date/time to get just the time - the date part will show as 00/01/1900 in this case. 或者,您可以删除日期/时间的整数以获取时间-在这种情况下,日期部分将显示为00/01/1900。 =A1-INT(A1)

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

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