从数字月份获取第一天和最后一天

时间:2019-10-01 12:32:53

标签: excel vba

假设在 A1 中,我有1月的 1 (对我来说是月数)。

在给定月份数字4 的情况下,如何获得当年的第一天天和最后一天? (如果可能,在VBA中)

没有尝试代码,因为我在互联网上只找到公式,但是没有月份号...

每个链接和建议也被接受

3 个答案:

答案 0 :(得分:3)

一个选项是DateSerialDateAdd

Sub Test()
    Dim monthNum As Long
    monthNum = 4

    Dim firstDay As Date
    firstDay = DateSerial(Year(Date), monthNum, 1)

    Dim lastDay As Date
    lastDay = DateAdd("m", 1, firstDay) - 1    
End Sub

编辑:您也可以在最后一天使用DateSerial

DateSerial(Year(Date), monthNumber + 1, 0)

答案 1 :(得分:2)

您可以尝试以下类似方法。绝对是一种解决方法,因为我敢肯定其他人会有更好的解决方案!

Option Explicit

Sub GetLastDay()

    Dim i As Long
    Dim lMonth As Long, dDateTest As Date

    'april
    lMonth = 4

    'first date
    Debug.Print "First day in month is always 1"

    'last day
    '31 is max in any given month
    For i = 1 To 32
        dDateTest = DateSerial(Year(Date), lMonth, i)
        If Month(dDateTest) <> lMonth Then
            Debug.Print "Last day in month = " & (i - 1)
            Exit For
        End If
    Next i

End Sub

结果打印出来:

Last day in month = 30

答案 2 :(得分:0)

我为您提供解决方案。假设您在A列中有月份数,并且同一月号的第一个日期和最后一个日期应分别在B列和C列中反映出来


Dim mnt As Long, xrow As Long
Dim i As Long, Ws As Worksheet
Set Ws = ThisWorkbook.Sheets("Sheet1")
xrow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row

For i = 2 To xrow
    Ws.Cells(i, 2).Value = "=date(year(today()),RC[-1],1)"
    Ws.Cells(i, 3).Value = "=eomonth(RC[-1],0)"
Next i

End Sub

希望有帮助