VBA - 访问 - 获取一个月的最后一天

lin*_*man 4 vba

我需要你的帮助.我想得到这个月的最后一天.这是我的代码,但如果我想调试它并将其编译到数据库,它说它在语法中有错误.请帮忙=)

Public Function GetNowLast() As Date
Dim asdfh As Date
asdfh = DateValue("1." _
& IIf(Month(Date) + 1) > 12, Month(Date) + 1 - 12, Month(Date) + 1) _
&"."&IIf(Month(Date)+1)>12 , Year(Date)+1,Year(Date))
asdf = DateAdd("d", -1, asdf)
GetNowLast = asdf
End Function
Run Code Online (Sandbox Code Playgroud)

mth*_*len 12

GD Linuxman,

让我们专注于获得结果... :-)

另见:这里

@Scott Craner的评论很有见!虽然严格来说,没有必要使用格式.(假设您想使用'Date'对象)

要实现您想要的功能,请按以下方式设置功能:

Function GetNowLast() as Date

    dYear = Year(Now)
    dMonth = Month(Now)

    getDate = DateSerial(dYear, dMonth + 1, 0)

    GetNowLast = getDate

End Function
Run Code Online (Sandbox Code Playgroud)

您可以在代码中调用该函数:

Sub findLastDayOfMonth()

    lastDay = GetNowLast()

End Sub
Run Code Online (Sandbox Code Playgroud)

或者,整洁可能:

Function GetNowLast(inputDate as Date) as Date

    dYear = Year(inputDate)
    dMonth = Month(inputDate)

    getDate = DateSerial(dYear, dMonth + 1, 0)

    GetNowLast = getDate

End Function
Run Code Online (Sandbox Code Playgroud)

您可以调用该函数并将其传递给输入参数.

Sub findLastDayOfMonth()

lastDay = GetNowLast(Now()) 'Or any other date you would like to know the last day of the month of.

End Sub
Run Code Online (Sandbox Code Playgroud)

另请参阅@KekuSemau的这个简洁的解决方案