【问题标题】:How to create a date using strings in vba?如何在 vba 中使用字符串创建日期?
【发布时间】:2015-06-15 12:38:14
【问题描述】:

我想从某个时间到某个特定时间运行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

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

【问题讨论】:

  • 你能用错误信息编辑你的问题吗?

标签: ms-access vba ms-access-2003


【解决方案1】:

DateSerial 应该会让这更容易。

按顺序为它提供年、月和日的值,它会将相应的日期作为日期/时间值返回给您。

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

【讨论】:

  • 不客气。当你说一年中的最后一天时,我不确定你在想什么。这让我想到DateSerial(rs!dan, 12, 31) 但我决定将你已经拥有的内容翻译成DateSerial
  • 没问题。我通常不会问我正在寻找的确切内容,我会寻找类似的东西,这样我才能弄清楚其余的东西。如果我问确切的事情,我会变得懒惰:D
【解决方案2】:

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

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。
  • 好的。正如您在上面看到的,我接受了日期序列不是我的答案。并且字符串路由是一种可能性,即使它是更有效的@Gustav
猜你喜欢
  • 2014-12-12
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 2018-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多