【问题标题】:DateAdd Function in Microsoft Access VBAMicrosoft Access VBA 中的 DateAdd 函数
【发布时间】:2016-09-20 21:55:22
【问题描述】:
我正在尝试在我的 Microsoft Access 2010 表单中实现 DateAdd 函数。我有一个表单,当用户输入日期时(名为“txtStartDate”的属性名称,然后我希望不同部分的输出为未来 18 个日历日(名为“textEndDate”的属性名称)。
我知道格式是
=DateAdd("d", 18, txtStartDate)
但是如何用VBA代码编写来实现呢?
【问题讨论】:
标签:
ms-access
vba
dateadd
【解决方案1】:
听起来您希望在更新后设置它。因此,使用开始日期的 AfterUpdate 事件:
Private Sub txtStartDate_AfterUpdate()
Dim EndDate As Variant
If IsDate(Me!txtStartDate.Value) Then
EndDate = DateAdd("d", 18, Me!txtStartDate.Value)
Else
EndDate = Null
End If
Me!txtEndDate.Value = EndDate
End Sub
【解决方案2】:
希望这会有所帮助,原始日期和新日期的两个声明。然后 Msgbox 在不同的行显示它们:
sub addingDate()
Dim txtStartDate As Date
Dim txtEndDate As Date
txtStartDate = Now 'Or wherever you get this info from
txtEndDate = DateAdd("d", 18, txtStartDate)
MsgBox (txtStartDate & vbNewLine & txtEndDate)
End Sub
【解决方案3】:
听起来您正在将文本框值从字符串隐式转换为日期。您可能需要添加一些检查,例如:
If IsDate(txtStartDate) Then
如果您的代码在美国/英国/日本日期的区域日期设置不同的系统上运行,您需要特别注意这种行为。 可能需要在控件本身上使用日期选择器或其他日期验证。
【解决方案4】:
您不需要 VBA 来执行此操作,只需一个表达式作为 ControlSource 用于其他文本框:
=DateAdd("d", 18, [txtStartDate])
【解决方案5】:
试试这个:
= DateAdd("d", 18, cdate(txtStartDate)