我需要做一个vba,将endDate设置到这个月的最后一天

我有一个开始date分配为startDate和另一个单元格分配endDate的2个单元格。 每次我点击单元格的日历popup,我inputdate。 我希望macros将endDate自动更改为月份的最后一天。 因此,当用户进入并input开始date时,macros将input该月的最后一天的结束date。 这里是我现在的代码:

Function dhLastDayInMonth(Optional endDate As Date = 0) As Date ' Return the last day in the specified month. If endDate = 0 Then ' Did the caller pass in a date? If not, use ' the current date. dtmDate = Date End If dhLastDayInMonth = DateSerial(Year(endDate), _ Month(dtmDate) + 1, 0) End Function 

还有以下是日历的代码:

 Option Explicit Private Sub Worksheet_SelectionChange(ByVal Target As Range) 'check cells for desired format to trigger the calendarfrm.show routine 'otherwise exit the sub Dim DateFormats, DF DateFormats = Array("m/d/yy;@", "mmmm d yyyy") For Each DF In DateFormats If DF = Target.NumberFormat Then If CalendarFrm.HelpLabel.Caption <> "" Then CalendarFrm.Height = 191 + CalendarFrm.HelpLabel.Height Else: CalendarFrm.Height = 191 CalendarFrm.Show End If End If Next End Sub 

在你的endDate单元格中,你可以使用这个公式:

 =DATE(YEAR(startDate),MONTH(startDate)+1,0) 

startDate是对startDate单元格的命名引用。

如果你真的热衷于使用自己的VBAfunction,那么你可以创build一个这样的函数,基本上获得下个月的第一天,并从它减去1天得到该月的最后一天。 我认为Thunderframe的答案是最好的,因为它很简单,并使用Excel的本地function。

 Public Function dhLastDayInMonth(Optional endDate As Date = 0) As Date Dim dt As Date 'check if we have a date If endDate = 0 Then ' Did the caller pass in a date? If not, use ' the current date. dt = DateTime.Now Else dt = endDate End If 'check for December If DatePart("m", dt) = 12 Then 'add one to the year and month dt = DateSerial(DatePart("yyyy", DateAdd("yyyy", 1, dt)), DatePart("m", DateAdd("m", 1, dt)), 1) Else 'add 1 to the month dt = DateSerial(DatePart("yyyy", dt), DatePart("m", DateAdd("m", 1, dt)), 1) End If 'subtract 1 day from the date to get the last date of the month dt = DateAdd("d", -1, dt) 'return the end of the month dhLastDayInMonth = dt End Function