Excel VBA 向日期/时间字符串添加 1 小时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31439282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:46:53  来源:igfitidea点击:

Excel VBA Adding 1 hour to a date / time string

excelvbaexcel-vbadatetime

提问by Shaves

I have a text string that looks like this: "06/10/15 4:53pm". I want to add 1 hour (60 minutes exactly) to the text string looks like this: "06/10/15 5:53pm"

我有一个看起来像这样的文本字符串:“06/10/15 4:53pm”。我想在文本字符串中添加 1 小时(正好是 60 分钟),如下所示:“06/10/15 5:53pm”

Any suggestions would be appreciated.

任何建议,将不胜感激。

回答by Don Jewett

Convert it to a date, add an hour, and convert back to string using format

将其转换为日期,添加一个小时,然后使用格式转换回字符串

Private Sub TestIt()

    MsgBox AddHour("06/10/15 4:53pm")

End Sub

Public Function AddHour(ByVal sTime As String) As String
    Dim dt As Date

    dt = CDate(sTime)
    dt = DateAdd("h", 1, dt)

    AddHour = Format(dt, "mm/dd/yy h:nnam/pm")

End Function

Reference:

参考:

回答by gokool108

No VBA needed...assuming the time value above(06/10/15 4:53pm) is in cell A1 the Formula you are looking for is:

不需要VBA...假设上面的时间值(06/10/15 4:53pm)在单元格A1中,您要查找的公式是:

=A1+TIME(1,0,0)

回答by Excel Hero

Since you asked for a VBA solution:

由于您要求提供 VBA 解决方案:

s = "06/10/15 4:53pm"

MsgBox CDate(s) + 1 / 24

回答by Sharunas Bielskis

For operations with date and time in VBA is DateAdd function. You can find how to use it in this link: https://www.techonthenet.com/excel/formulas/dateadd.php

对于 VBA 中的日期和时间操作是 DateAdd 函数。您可以在此链接中找到如何使用它:https: //www.techonthenet.com/excel/formulas/dateadd.php