在VBA中查找一个月或一年的第一天和最后一天的最简单方法

问题描述 投票:2回答:3

选择年份和月份的两个下拉菜单。在月份下拉列表中有选项JAN,FEB,MAR....DEC and ALL。在2016,2017,2018,2019,2020

我需要一个返回该选择的第一天的函数。如果选择2017 and All,它应该返回01/01/2017。如果它的2017 and JUL,返回值应该是2017年7月1日

另一个功能正好相反。如果用户给2018 and All,它应该返回31/12/2018。如果用户给2018 and FEB,它应该返回28/02/2018

那么哪个是这种情况的最佳解决方案..

我第一天尝试的内容如下

Function firstDay(year As String, month As String) As Date
    Dim fd As Date
    If LCase(month) = "all" Then month = "JAN"
    fd = DateValue("01 " & month & Space(1) & year)
    firstDay = fd
End Function

但是对于最后一天我没有得到如何做到这一点,或者我尝试的解决方案并不是很好。期待更好的解决方案(当然,如果有更好的选择,第一天也是如此)

vba excel-vba excel
3个回答
2
投票

这应该适用于所有月份,无论它们有多长:

Function lastDay(year As String, month As String) As Date
    Dim fd As Date
    If LCase(month) = "all" Then month = "DEC"
    fd = DateValue("01 " & month & Space(1) & year) + 32
    fd = fd - Day(fd)
    lastDay = fd
End Function

1
投票

我共享一个我创建的功能,以达到目的。所以对于那些有类似要求的人可以使用

Function lastDay(year As String, month As String) As Date
    Dim ld As Date
    If LCase(month) = "all" Then month = "DEC"
    ld = DateValue("01 " & month & Space(1) & year)
    Dim d As Double
    d = WorksheetFunction.EoMonth(ld, 0)
    ld = CDate(d)
    lastDay = ld
End Function

1
投票

这是我的功能版本。

Function endofdates(yr As Integer, _
                    mth As Integer, _
                    Optional firstday As Boolean = True) As Date
    If firstday Then
        endofdates = DateSerial(yr, mth, 0) + 1
    Else
        endofdates = DateSerial(yr, mth + 1, 0)
    End If
End Function

编辑1:重新阅读你的问题,发现你不能在上面使用,所以我重写了它,以满足你的需求。

Function endofdates(yr As Integer, _
                    mth_name As String, _
                    Optional firstday As Boolean = True) As Date
    Dim mth As Integer, idx As Integer
    Const mlist As String = "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"
    idx = InStr(1, mlist, mth_name, vbTextCompare)
    mth = Int(idx / 3) + (idx Mod 3)
    If firstday Then
        If mth = 0 Then mth = 1
        endofdates = DateSerial(yr, mth, 0) + 1
    Else
        If mth = 0 Then yr = yr + 1
        endofdates = DateSerial(yr, mth + 1, 0)
    End If
End Function

Edit2:我猜你使用DateValue的逻辑更简单:

Function endofdates(yr As Integer, _
                    mth_name As String, _
                    Optional firstday As Boolean = True) As Date
    Dim dt As Date
    If firstday Then
        If LCase$(mth_name) = "all" Then mth_name = "jan"
        dt = DateValue("1 " & mth_name & " " & yr)
    Else
        If LCase$(mth_name) = "all" Then mth_name = "dec"
        dt = DateValue("1 " & mth_name & " " & yr)
        dt = DateSerial(Year(dt), Month(dt) + 1, 0)
    End If
    endofdates = dt
End Function
© www.soinside.com 2019 - 2024. All rights reserved.