如何使用 vba 中的字符串创建日期?

How to create a date using strings in vba?

我想 运行 一个 for-loop 从某个时间到某个特定时间。假设从一年的第一天到最后一天:

我得到了年份,我需要添加月份和日期:

我正在尝试连接成一个完整的日期字符串,但编译器不断抛出错误:

dim dt as Date 
dim rs as recordset 
set rs = currentdb.openRecordset("select max(date) as dan from Atbl")

for dt = #1/1/year(now)# to #2/2/Year(rs!dan)#
    msgbox dt
Next

感谢任何帮助。或者欢迎任何提示

没关系,我很快找到了解决方案:这个很好用

dim dt as Date 
dim rs as recordset 
set rs = currentdb.openRecordset("select max(date) as dan from Atbl")

'save the first day as string first
Dim firstDay As String
firstDay = "1/1/" & Year(Now)
'convert to date
Dim firstDate As Date
firstDate = CDate(firstDay)

'save as string
Dim lastDay as string 
lastDay = "2/2/" & Year(rs!dan)

'convert to date
Dim lastDate As Date
lastDate = CDate(lastDay)

'works fine in here
for dt = firstDate to lastDate
    msgbox dt
next

DateSerial 应该会让这更容易。

按年、月、日的顺序给它值,它会返回相应的日期作为 Date/Time 值。

for dt = DateSerial(Year(Date), 1, 1) to DateSerial(rs!dan, 2, 2)
    msgbox dt
Next