我正在学习 VBA 基础知识。我在变量中有日、月、年、小时、分钟、秒数据。如何从这些值构造日期时间对象?
最佳答案
通常,日期将被表示为 Date
数据类型。日期存储为 double 数字,表示自 1899 年 12 月 31 日以来的天数。时间表示为一天的一小部分,例如上午 6:00 用 0.25 表示。
然后,您可以使用以下方法为 Date 变量赋值
Dim myDate As Date
myDate = Now()
myDate = DateValue("30 July 2016")
myDate = DateSerial(2016,7,30)
' or even myDate = DateSerial(2016,7,30+20) which is equivalent to myDate = DateSerial(2016,8,19)
myDate = TimeValue("19:22:56")
或者,如果您有包含年、月、日等的变量,您可以将日期值计算为
myDate = DateSerial(myYear, myMonth, myDay) + TimeSerial(myHour, myMinute, mySecond)
如果您不想使用
Date
数据类型,您可以使用类似的东西创建自己的Type myDateType
myDay as Integer
myMonth as Integer
myYear as Integer
myHour as Integer
myMinute as Integer
mySecond as Integer
End Type
然后通过类似的方式声明变量
Dim myDateVariable as myDateType
并通过类似的方式引用类型的各个部分
myDateVariable.myYear = 2016
关于vba - 如何在 VBA 中为宏编程定义自定义日期时间对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38672269/