每个月的月末

时间:2015-02-25 08:21:16

标签: excel vba datepicker userform

在excel的用户表单中,使用vba,我需要查找月末。例如,我的开始日期是01.01.2015,结束日期将自动为31.01.2015.I尝试使用此代码:< / p>

Private Function dhLastDayInMonth(Optional dtmDate As Date = 0) As Date
    ' Return the last day in the specified month.

If dtmDate = 0 Then
        ' Did the caller pass in a date? If not, use
        ' the current date.
        dtmDate = Date
End If

dhLastDayInMonth = DateSerial(Year(dtmDate), _
     Month(dtmDate) + 1, 0)

End Function

但此代码仅返回2月底。 例: 开始日期:01.01.2015我的代码返回28.02.2015 或开始日期:05.02.2015我的代码返回28.02.2015

seconde代码行是编辑文本框以插入结束日期

Private Sub txtEDate_Change()

If txtEDate.Text = "" Then
    MsgBox "You must enter a Date! "
    Exit Sub
End If

If txtEDate.TextLength = 2 Or txtEDate.TextLength = 5 Then
    txtEDate.Text = txtEDate.Text + "."
End If

If txtEDate.TextLength = 2 Or txtEDate.TextLength = 5 Then
txtEDate.Text = txtEDate.Text + "DD/MM/YYYY"
End If

txtEDate.Text = dhLastDayInMonth()

End Sub

1 个答案:

答案 0 :(得分:0)

您必须将年份和月份定义为输入以获取当月的最后日期:

Public Function LastDayInMonth(dIn As Date) As Date
    LastDayInMonth = DateSerial(Year(dIn), Month(dIn) + 1, 0)
End Function

将在某个月内给出最后一个日期,但前提是 dIn 具有正确的值。

显然,您应该在UDF顶部 MsgBox dtmDate