访问 - 使用日期(如果可用),否则使用今天的日期

时间:2017-06-28 17:20:05

标签: vba date ms-access access-vba

所以这让我发疯,这应该是非常容易的。我不知道为什么我无法让它发挥作用。 :(目前我的功能是计算开始日期和今天的日期之间的差异,它工作得很好,但现在我需要实现一个可选的结束日期。所以如果有可用的EmpEndDate,它应该被使用,否则应该使用今天的日期。

这是我的一个职能部门:

Public Function RetentionMonths(ByVal EmpStartDate As Date) As Integer

    Dim RetentionStartdate As Date
    Dim FollowingMonth As Date

        RetentionStartdate = DateAdd("ww", 14, DateAdd("d", vbSaturday - Weekday(EmpStartDate), EmpStartDate))
        FollowingMonth = DateSerial(Year(RetentionStartdate), Month(RetentionStartdate) + 1, 1)
        RetentionMonths = Months(FollowingMonth, Date)

End Function

编辑:Months()函数

Public Function Months( _
  ByVal datDate1 As Date, _
  ByVal datDate2 As Date, _
  Optional ByVal booLinear As Boolean) _
  As Integer

  Dim intDiff   As Integer
  Dim intSign   As Integer
  Dim intMonths As Integer

  intMonths = DateDiff("m", datDate1, datDate2)

  If DateDiff("d", datDate1, datDate2) > 0 Then
    intSign = Sgn(DateDiff("d", DateAdd("m", intMonths, datDate1), datDate2))
    intDiff = Abs(intSign < 0)
  Else
    intSign = Sgn(DateDiff("d", DateAdd("m", -intMonths, datDate2), datDate1))
    If intSign <> 0 Then
      intDiff = Abs(booLinear)
    End If
    intDiff = intDiff - Abs(intSign < 0)
  End If

  Months = intMonths - intDiff

End Function

我试图解决这个问题的一种方式:

Public Function RetentionMonths(ByVal EmpStartDate As Date, _
    Optional ByVal EmpEndDate As Date) _
    As Integer

    Dim RetentionStartdate As Date
    Dim FollowingMonth As Date

        RetentionStartdate = DateAdd("ww", 14, DateAdd("d", vbSaturday - Weekday(EmpStartDate), EmpStartDate))
        FollowingMonth = DateSerial(Year(RetentionStartdate), Month(RetentionStartdate) + 1, 1)
        RetentionMonths = Months(FollowingMonth, Nz(EmpEndDate, Date))

End Function

我要么在以前工作的字段中使用疯狂的负数,要么是#Name?错误。

1 个答案:

答案 0 :(得分:0)

您可以使用clng

检查结束日期的值0
Public Function RetentionMonths(ByVal EmpStartDate As Date, _
    Optional ByVal EmpEndDate As Date) _
    As Integer

    Dim RetentionStartdate As Date
    Dim FollowingMonth As Date
    Dim tempEndDate As Date

    If CLng(EmpEndDate) = 0 Then EmpEndDate = Now()


        RetentionStartdate = DateAdd("ww", 14, DateAdd("d", vbSaturday - Weekday(EmpStartDate), EmpStartDate))
        FollowingMonth = DateSerial(Year(RetentionStartdate), Month(RetentionStartdate) + 1, 1)
        RetentionMonths = Months(FollowingMonth, Nz(EmpEndDate, Date))

End Function