我正在处理 Outlook 的 VBA 项目。该项目正在查看日历约会并将它们与从 SQL 数据库中提取并存储在日期变量中的日期进行比较。
目前,当日期从 SQL 数据库中出来时,它们没有任何时间组件,但我想添加一个。
例如,SQL 查询中出现“07/03/2018”,我希望能够将其设置为“07/03/2018 09:00:00”和一天中的其他各种时间。
有没有一种方法可以不将日期变量转换为字符串并在末尾添加时间?这是因为我希望能够在程序稍后的变量上使用基于日期的函数,例如 DateAdd 等。
最佳答案
有很多方法可以将日期和时间相加。
这里有一些我头脑中的想法:
Sub examples()
'store an example date
Dim dt As Date
dt = CDate("March 7, 2018")
'now to add 9 hours:
Debug.Print dt + (9 / 24)
'or, using DateAdd:
Debug.Print DateAdd("h", 9, dt)
'or, add a time:
Dim tm As Date
tm = CDate("9:00 am")
Debug.Print dt + tm
'or, as text:
Dim str As String
str = Format(dt, "mmm d, yyyy")
str = str & " 9:00 am"
Debug.Print CDate(str)
'or, with TimeValue:
Debug.Print dt + TimeValue("9:00")
'or, get extract the date from a datettime and add a different time:
Debug.Print DateValue(Now()) + TimeValue("9:00")
End Sub
哪种方法最好取决于您要用它做什么。
日期只是数字
在 Excel 和 VBA 中,日期(或 DateTimes)只是数字开始于:
Midnight on "January 0, 1900"
...并且每天增加 1
。
1 = January 1, 1900, 00:00:00 (00:00 = midnight)
2 = January 2, 1900, 00:00:00
43166 = March 7, 2018
需要在 1900 年 1 月 2 日上午 9:00 之前到达?
1 小时是一天中的 1/24。
∴
9:00 am
=(9 ÷ 24)
=0.375
∴
2.375
=1900 年 1 月 2 日上午 9:00
类似地:
∴
9:00 pm
=(18 ÷ 24)
=0.875
∴
2.875
=1900 年 1 月 2 日晚上 9:00
6:00am = 0.25(¼ 天) 中午 = 0.5(½ 天) 下午 6:00 = 0.75(¾ 天)
1 小时 ≈ 0.417 1 分钟 ≈ 0.000695 1 秒 ≈ 0.000011574
离夏天还有多少天?
Today = 43166 (March 7, 2018)
Summer begins = 43272 (June 21, 2018) [Northern Hemisphere]
43272 - 43166 = 106 days
离夏天还有几个小时?
106 × 24 = 2544 hours
...你明白了。 ☺
Excel 中可能的最长时间:
Friday, December 31, 9999 23:59:59 = 2958465.99998843
(...所以不要为那个周末制定任何计划。)
更多信息:
关于vba - 在 VBA 中更改或添加时间到日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49152241/